Searches an element in the given Iterable instance. - Java java.util

Java examples for java.util:Iterable Element

Description

Searches an element in the given Iterable instance.

Demo Code

/*******************************************************************************
 * Copyright (c) 2014 Karlsruhe Institute of Technology, Germany
 *                    Technical University Darmstadt, Germany
 *                    Chalmers University of Technology, Sweden
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:// w  w w . j  av  a  2s  .  c  o m
 *    Technical University Darmstadt - initial API and implementation and/or initial documentation
 *******************************************************************************/
import java.util.Iterator;
import java.util.function.Predicate;

public class Main {
  /**
   * Searches an element in the given {@link Iterable} instance.
   * 
   * @param iterable
   *          The instance to search in.
   * @param filter
   *          The filter to select an element.
   * @return The found element or {@code null} if no element was found.
   */
  public static <T> T search(Iterable<T> iterable, Predicate<T> filter) {
    T result = null;
    if (iterable != null && filter != null) {
      Iterator<T> iter = iterable.iterator();
      if (iter != null) {
        while (result == null && iter.hasNext()) {
          T next = iter.next();
          if (filter.test(next)) {
            result = next;
          }
        }
      }
    }
    return result;
  }
}

Related Tutorials