jdk1.8 新特性 lambda表达式常用方法

jdk8新增特性之一,流运算很方便,本文提供了常见的使用方式
注:流循环之中不能使用外部引用变量,不共享变量

package com.example;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created By JGMa on 2020-07-01
 */
public class TestLambda {

    private static List<Person> list = new ArrayList<>();

    static {
        /**
         * Person实体字段:
         *     private String name;
         *     private String address;
         *     private int age;
         *     private int sort;
         */
        Person p1 = new Person("张1", 1, 1);
        Person p2 = new Person("张2", 2, 2);
        Person p3 = new Person("张3", 2, 3);
        Person p4 = new Person("张4", 4, 4);
        Person p5 = new Person("张5", 5, 5);
        Person p6 = new Person("张6", 6, 6);
        Person p7 = new Person("张2", 2, 7);
        list.add(p1);
        list.add(p3);
        list.add(p2);
        list.add(p5);
        list.add(p4);
        list.add(p6);
        list.add(p7);
    }

    public static void main(String[] args) {

        /**
         * 2. stream()流操作
         */
        // 2.11 去重 distinct() 去重;collect(Collectors.toList())。封装成集合
        List<Person> distinctList = list.stream().distinct().collect(Collectors.toList());

        // 2.12 根据age去重 , 利用 TreeSet 的排序去重构造函数来达到去重元素的目的
        ArrayList<Person> distinctAgeList = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
                () -> new TreeSet<>(Comparator.comparing(Person::getAge))), ArrayList::new));
        printList(distinctAgeList);

        //2.2 排序  sorted((第一个对象,第二个对象)->返回值)  (升降序看是第几个对象与第几个对象比较)
        List<Person> sortedList = list.stream().sorted((o1, o2) -> o1.getSort() - o2.getSort()).collect(Collectors.toList());
//        printList(sortedList);

        //2.3 过滤 按照自己的需求来筛选list中的数据
        List<Person> filterList = list.stream().filter(item -> item.getAge() > 3).collect(Collectors.toList());
//        printList(filterList);

        //2.4 map(), 提取对象中的某一元素.  用每一项来获得属性(也可以直接用  对象::get属性())
        List<String> mapList1 = list.stream().map(Person::getName).collect(Collectors.toList());
        List<String> mapList2 = list.stream().map(item -> item.getName()).collect(Collectors.toList());
//        for (String s : mapList2) {
//            System.out.println(s);
//        }

        //2.5 统计 sum() 。mapToDouble() 转换成double。还有其他类型转换。可以自己研究。
        //           max(),min(),average()
        double sum = list.stream().mapToDouble(Person::getAge).sum();
        double asDouble = list.stream().mapToInt(item -> item.getAge()).average().getAsDouble();
//        System.out.println(asDouble);

        //2.6 分组   Collectors.groupingBy(属性名)
        Map<Integer, List<Person>> map = list.stream().collect(Collectors.groupingBy(Person::getAge));
//        for (Map.Entry<Integer, List<Person>> entry : map.entrySet()) {
//            System.out.println(entry.getKey()+"===="+entry.getValue());
//        }

        //2.7 多重分组 Collectors.groupingBy(属性,Collectors.groupingBy(属性))
        Map<String, Map<Integer, List<Person>>> map2 = list.stream().collect(Collectors.groupingBy(t -> t.getName(), Collectors.groupingBy(t -> t.getAge())));
//        for (Map.Entry<String, Map<Integer, List<Person>>> stringMapEntry : map2.entrySet()) {
//            String key = stringMapEntry.getKey();
//            Map<Integer, List<Person>> mapValue = stringMapEntry.getValue();
//            for (Map.Entry<Integer, List<Person>> entry : mapValue.entrySet()) {
//                System.out.println(key + "==>  " + entry.getKey() + ":" + entry.getValue());
//            }
//        }

        //2.8 分组并计算综合        Collectors.summarizingLong()
        Map<String, Map<Integer, Integer>> map3 = list.stream().collect(
                Collectors.groupingBy(t -> t.getName(),
                        Collectors.groupingBy(t -> t.getAge(),
                                Collectors.summingInt(Person::getSort))));
        // 使用summarizingLong
//        Collectors.summarizingLong(Person::getSort)
//        结果:LongSummaryStatistics{count=1, sum=1, min=1, average=1.000000, max=1}
//        for (Map.Entry<String, Map<Integer, LongSummaryStatistics>> stringMapEntry : map3.entrySet()) {
//            String key = stringMapEntry.getKey();
//            Map<Integer, LongSummaryStatistics> value = stringMapEntry.getValue();
//            for (Map.Entry<Integer, LongSummaryStatistics> entry : value.entrySet()) {
//                System.out.println(key + "==> " + entry.getKey() + ":" + entry.getValue());
//            }
//        }
        // 使用单独计算函数 summingInt
//        for (Map.Entry<String, Map<Integer, Integer>> stringMapEntry : map3.entrySet()) {
//            String key = stringMapEntry.getKey();
//            Map<Integer, Integer> value = stringMapEntry.getValue();
//            for (Map.Entry<Integer, Integer> entry : value.entrySet()) {
//                System.out.println(key + "==> 年龄:" + entry.getKey() + "= [分组后sort总和:" + entry.getValue()+"]");
//            }
//        }

//        printList(list);
//        System.out.println("======== 排序后 ======");
        /**
         *  3.  集合比较的简写方式
         */
        list.sort((o1, o2) -> {
            return o1.getAge() - o2.getAge();
        });
//        printList(list);
    }

    public static void printList(List<Person> list) {
        /**
         * 1.forEach()进行遍历集合
         *    item:可以是任意值。类似于for循环中的循环值
         */
        list.forEach(item -> {
            //设置值
            item.setName(item.getName() + "测试");
            //输出语句
            System.out.println(item.toString());
        });
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值