Lambda 表达式的常见用法

文章目录

  • Lambda 表达式的常见用法
    • 使用Lambda表达式集合遍历
    • 使用Lambda表达式排序
    • 使用Lambda表达式过滤
    • 使用Lambda表达式映射
    • 使用Lambda表达式归约
    • 使用Lambda表达式分组
    • 使用Lambda表达式函数式接口的实现
    • 使用Lambda表达式线程的创建
    • 使用Lambda表达式进行Optional 操作
    • 使用Lambda表达式进行Stream的流操作

Lambda 表达式的常见用法

使用Lambda表达式集合遍历

/*遍历集合*/
List<String> fruitList = Arrays.asList("apple","banana","orange","mango","grape");
//传统方式
for (String s : fruitList) {
    System.out.println(s);
}
//lambda
fruitList.forEach(System.out::println);

使用Lambda表达式排序

        /*集合排序*/
        List<String> fruitList = Arrays.asList("apple","banana","orange","mango","grape");
        //传统方式
        Collections.sort(fruitList, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        //lambda
        Collections.sort(fruitList, ((o1, o2) -> o1.compareTo(o2)));

使用Lambda表达式过滤

        /*集合过滤 拿到首字母是 a 的元素*/
        List<String> fruitList = Arrays.asList("apple","banana","orange","mango","grape");
        //传统
        List<String> list1 = new ArrayList<>();
        for (String s : fruitList) {
            if (s.startsWith("a")) {
                list1.add(s);
            }
        }

        //lambda
        List<String> list2 = fruitList.stream().filter(s -> s.startsWith("a")).collect(Collectors.toList());

使用Lambda表达式映射

        /*集合映射 映射出字段的长度*/
        List<String> fruitList = Arrays.asList("apple","banana","orange","mango","grape");
        //传统
        List<Integer> list1 = new ArrayList<>();
        for (String s : fruitList) {
            list1.add(s.length());
        }

        //lambda
        List<Integer> list2 = fruitList.stream().map(s -> s.length()).collect(Collectors.toList());

使用Lambda表达式归约

        /*集合归约 list 所有字段累加*/
        List<Integer> sumList = Arrays.asList(1,2,3,4,5,6,8);
        //传统
        int sum1 = 0;
        for (Integer v : sumList) {
            sum1 += v;
        }

        //lambda
        Integer sum2 = sumList.stream().reduce(0, (a, b) -> a + b);

使用Lambda表达式分组

        /*集合分组 list字段的长度进行分组*/
        List<String> fruitList = Arrays.asList("apple","banana","orange","mango","grape");
        //传统
        Map<Integer, List<String>> group1 = new HashMap<>();
        for (String s : fruitList) {
            if (!group1.containsKey(s.length())){
                group1.put(s.length(), new ArrayList<>());
            }
            group1.get(s.length()).add(s);
        }
        //lambda
        Map<Integer, List<String>> group2 = fruitList.stream().collect(Collectors.groupingBy(String::length));

使用Lambda表达式函数式接口的实现

        //接口
        interface MyInterface {
            public void doSomething(String s);
        }
        /*实现接口*/
        //传统方法
        MyInterface myInterface1 = new MyInterface() {
            @Override
            public void doSomething(String s) {
                System.out.println(s);
            }
        };

        //lambda
        MyInterface myInterface2 = (s) -> System.out.println(s);
        //或者
        MyInterface myInterface3 = System.out::println;

使用Lambda表达式线程的创建

        /*创建线程  实际开发中不要显示创建线程,最好用线程池*/
        //传统
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello World");
            }
        });
        thread.start();

        //lambda
        Thread thread1 = new Thread(() -> System.out.println("Hello World"));
        Thread thread2 = new Thread(System.out::println);
        Thread thread3 = new Thread(LambdaUsefullness::listreduceSum);

		/*使用线程池举例*/
		ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 5, 2L
                , TimeUnit.SECONDS
                , new LinkedBlockingDeque<>(4)
                , Executors.defaultThreadFactory()
                , new ThreadPoolExecutor.AbortPolicy());
        executor.execute(() ->{
            for (int i = 0; i < 10 ; i++) {
                System.out.println("Hello World分支线程===="+i);
            }
        });

使用Lambda表达式进行Optional 操作

        /*Lambda 方式配合Optional 操作*/
        String str = "Hello world";
        //传统校验
        if (!str.isEmpty()) {
            System.out.println(str.toUpperCase());
        }
        //lambda
        Optional.ofNullable(str).map(String::toUpperCase).ifPresent(System.out::println);

使用Lambda表达式进行Stream的流操作

        /*lambda流操作 过滤包含 n 的字符串,并转大写,最后排序*/
        List<String> fruitList = Arrays.asList("apple","banana","orange","mango","grape");
        //传统
        List list1 = new ArrayList();
        for (String s : fruitList) {
            if (s.contains("n")) {
                list1.add(s.toUpperCase());
            }
        }
        Collections.sort(list1);

        //lambda
        List<String> list2 = fruitList.stream().filter(s -> s.contains("n"))
        .map(String::toUpperCase).sorted().collect(Collectors.toList());

你可能感兴趣的:(lambda,java,开发)