003.函数式编程(函数式接口Predicate)

1.函数式接口Predicate

 

 2.代码示例

package com.imooc.lambda;


import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 常务函数式接口Predicate函数式接口的使用方法
 */
public class PredicateSample
{
    public static void main(String[] args)
    {
        Predicate<Integer> predicate = n -> n < 4;
        boolean result = predicate.test(10);
        System.out.println(result);

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        filter(list, n -> n % 2 == 1);//取所有奇数
        filter(list, n -> n % 2 == 0);//取所有偶数
        filter(list, n -> n > 4 && n % 2 == 0);//取所有>5的偶数
    }

    public static void filter(List<Integer> list, Predicate<Integer> predicate)
    {
        for (Integer num : list)
        {
            if (predicate.test(num))
            {
                System.out.println(num + " ");
            }
        }
    }
}

 

posted @ 2023-01-06 23:35  李林林  阅读(25)  评论(0编辑  收藏  举报