Lamba表达式的几种应用

Posted zhumian

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lamba表达式的几种应用相关的知识,希望对你有一定的参考价值。

 

public class LambdaPrac {

    /**
     * 迭代
     */
    @Test
     public void demo1(){
         List list = Arrays.asList("jinx","timo","ez");
         list.forEach(n -> System.out.println(n));
     }

    /**
     * 函数式接口Predicate
     */
    @Test
     public void demo2(){
         List<String> list = Arrays.asList("jinx","timo","ez");
         filter(list,(String str) -> str.startsWith("j"));
     }

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

    /**
     * lambda表达式中加入predicate
     */
    @Test
     public void demo3(){
        List<String> list = Arrays.asList("jinx","timo","ez");
        Predicate<String> startWithJ = (n) -> n.startsWith("j");
        Predicate<String> fourLetterLong = (n) -> n.length() == 4;
        list.stream().filter(startWithJ.and(fourLetterLong)).forEach(n -> System.out.println(n));
     }

    /**
     * map的使用
     */
    @Test
     public void demo4(){
        List<Integer> cost = Arrays.asList(100,200,300,400,500);
        cost.stream().map((c) -> c + 100).forEach(System.out::println);
     }

    /**
     * 对列表每个元素应用函数
     */
    @Test
     public void demo5(){
         List<String> list = Arrays.asList("jinx","timo","ez");
         String s = list.stream().map(x -> x.toUpperCase()).collect(Collectors.joining(","));
         System.out.println(list.stream().count());
         System.out.println(s);
     }

    /**
     *求和
     */
    @Test
     public void demo6(){
         List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
         System.out.println(primes.stream().reduce(Integer::sum).get());
     }

    /**
     * 分组
     */
    @Test
     public void demo7(){
         List<String> list = Arrays.asList("day", "walipo", "day", "walipo", "legeand", "day", "douwbo", "day", "day");
         Map<String, Long> collect = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
         System.out.println(collect);
     }
}

 

以上是关于Lamba表达式的几种应用的主要内容,如果未能解决你的问题,请参考以下文章

一张图,理顺 Spring Boot应用在启动阶段执行代码的几种方式

一张图,理顺 Spring Boot应用在启动阶段执行代码的几种方式

一张图帮你记忆,Spring Boot 应用在启动阶段执行代码的几种方式

Laravel:如何在控制器的几种方法中重用代码片段

python lamba表达式

python lamba表达式写法