[JDK 8 - 関数型プログラミング] 4.5 述語

1.述語

2. 実戦: リスト内の a で始まる文字列を決定します。

ステージ 1: メソッドの作成

ステージ 2: メソッドの呼び出し

ステージ 3: 実行結果


1.述語

  • アサーティブインターフェイス: T: 入力パラメータの型、戻り値の型 ブール値

  • 呼び出しメソッド: boolean test(T t);

  • 目的:パラメータを受信して​​、特定の条件が満たされているかどうかを判断し、データをフィルタリングします。

/**
 * @param <T> the type of the input to the predicate
 */
@FunctionalInterface
public interface Predicate<T> {

    boolean test(T t);
}

2. 実戦:リスト内の a で始まる文字列を決定します。

ステージ 1: メソッドの作成

    public static List<String> filter(List<String> list, Predicate<String> predicate) {
        List<String> results = new ArrayList<>();
        list.forEach(s -> {
            if (predicate.test(s)) {
                results.add(s);
            }
        });
        return results;
    }

ステージ 2: メソッドの呼び出し

    public static void main(String[] args) {
        List<String> list = Arrays.asList("alis", "bron", "caiwen", "duo", "fanc", "abc");
        List<String> results = filter(list, obj -> obj.startsWith("a"));
        log.info(list.toString());
        log.info(results.toString());

    }

ステージ 3: 実行結果

おすすめ

転載: blog.csdn.net/ladymorgana/article/details/132988750