集册 Java实例教程 找到数组中与谓词匹配的第一个元素。

找到数组中与谓词匹配的第一个元素。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

513
找到数组中与谓词匹配的第一个元素。
/*from 时 代 J a v a - N o w J a v a . c o m*/

import java.util.Arrays;


public class Main{

    /**

     * Find the first element in the array that matches the predicate.

     * 

     * @param <T>       The type of element to use.

     * @param input     The array of candidates to match. Not null.

     * @param predicate The match condition. Not null.

     * @return The first match or null if there is none.

     */

    public static <T> T findFirstMatch(T[] input, Predicate<T> predicate) {

        assert input != null : "Illegal null value as parameter";

        assert predicate != null : "Illegal null value as parameter";


        for (T element : input) {

            if (predicate.matches(element)) {

                return element;

            }

        }
        /*
        NowJava.com - 时  代  Java 提供
        */

        return null;

    }

    /**

     * Find the first element in the array that matches the predicate.

     * 

     * This is a two-dimensional version of {@link #findFirstMatch(T[], Predicate)},

     * iteration is right-to-left as usual in Java. 

     * 

     * @param <T>       The type of element to use.

     * @param input     The array of candidates to match. Not null.

     * @param predicate The match condition. Not null.

     * @return The first match or null if there is none.

     */

    public static <T> T findFirstMatch(T[][] input, Predicate<T> predicate) {

        assert input != null : "Illegal null value as parameter";

        assert predicate != null : 
展开阅读全文