java8 新特性 Stream流 分组 排序 过滤 多条件去重 (最小、最大、平均、求和)

什么是 Stream?

Stream 是用函数式编程方式在集合类上进行复杂操作的工具,其集成了Java 8中的众多新特性之一的聚合操作,开发者可以更容易地使用Lambda表达式,并且更方便地实现对集合的查找、遍历、过滤以及常见计算等。话不多说,直接上代码。

List<User> list = new ArrayList<User>();
list =  Arrays.asList(
        new User("小强", 11, "男"),
        new User("小玲", 15, "女"),
        new User("小虎", 23, "男"),
        new User("小雨", 26, "女"),
        new User("小飞", 19, "男"),
        new User("小玲", 15, "女")
);
//分组
Map<String, List<User>> listMap = list.stream().collect(Collectors.groupingBy(User::getSex));
for(String key:listMap.keySet()){
    System.out.print(key+"组:");
    listMap.get(key).forEach(user -> System.out.print(user.getName()));
    System.out.println();
}
//排序
list.stream().sorted(Comparator.comparing(user-> user.getAge()))
        .forEach(user -> System.out.println(user.getName()));
//过滤
list.stream().filter(user -> user.getSex().equals("男")).collect(Collectors.toList())
        .forEach(user -> System.out.println(user.getName()));
//多条件去重
list.stream().collect(Collectors.collectingAndThen(
        Collectors.toCollection(() -> new TreeSet<>(
                Comparator.comparing(user -> user.getAge() + ";" + user.getName()))), ArrayList::new))
        .forEach(user -> System.out.println(user.getName()));
//最小值
Integer min = list.stream().mapToInt(User::getAge).min().getAsInt();
//最大值
Integer max = list.stream().mapToInt(User::getAge).max().getAsInt();
//平均值
Double average = list.stream().mapToInt(User::getAge).average().getAsDouble();
//和
Integer sum = list.stream().mapToInt(User::getAge).sum();
System.out.println("最小值:"+min+", 最大值"+max+", 平均值:"+average+", 和:"+sum);
//分组求和
Map<String, IntSummaryStatistics> collect = list.stream().collect(Collectors.groupingBy(User::getSex, Collectors.summarizingInt(User::getAge)));
IntSummaryStatistics statistics1 = collect.get("男");
IntSummaryStatistics statistics2 = collect.get("女");
System.out.println(statistics1.getSum());
System.out.println(statistics1.getAverage());
System.out.println(statistics1.getMax());
System.out.println(statistics1.getMin());
System.out.println(statistics1.getCount());
System.out.println(statistics2.getSum());
System.out.println(statistics2.getAverage());
System.out.println(statistics2.getMax());
System.out.println(statistics2.getMin());
System.out.println(statistics2.getCount());
//提取list中两个属性值,转为map
Map<String, String> userMap = list.stream().collect(Collectors.toMap(User::getName, User::getSex));
System.out.println(JsonUtil.toJson(userMap))
//取出所有名字
List<String> names = list.stream().map(User::getName).collect(Collectors.toList());
System.out.println(JsonUtil.toJson(names))

你可能感兴趣的:(java)