Lambda收集器示例

4 篇文章 0 订阅

Collectors常用方法

工厂方法返回类型作用
toSetSet把流中所有项目收集到一个 Set,删除重复项
toListList收集到一个 List 集合中
toCollectionCollection把流中所有项目收集到给定的供应源创建的集合menuStream.collect(toCollection(), ArrayList::new)
countingLong计算流中元素的个数
summingIntInteger对流中项目的一个整数属性求和
averagingIntDouble计算流中项目 Integer 属性的平均值
summarizingIntIntSummaryStatistics收集关于流中项目 Integer 属性的统计值,例如最大、最小、 总和与平均值
joiningString连接对流中每个项目调用 toString 方法所生成的字符串collect(joining(", "))
maxByOptional一个包裹了流中按照给定比较器选出的最大元素的 Optional, 或如果流为空则为 Optional.empty()
minByOptional一个包裹了流中按照给定比较器选出的最小元素的 Optional, 或如果流为空则为 Optional.empty()
reducing归约操作产生的类型从一个作为累加器的初始值开始,利用 BinaryOperator 与流 中的元素逐个结合,从而将流归约为单个值累加int totalCalories = menuStream.collect(reducing(0, Dish::getCalories, Integer::sum));
collectingAndThen转换函数返回的类型包裹另一个收集器,对其结果应用转换函数int howManyDishes = menuStream.collect(collectingAndThen(toList(), List::size))
groupingByMap<K, List>根据项目的一个属性的值对流中的项目作问组,并将属性值作 为结果 Map 的键
partitioningByMap<Boolean,List>根据对流中每个项目应用谓词的结果来对项目进行分区

 

示例

Apple 类

public class Apple {
    private Integer id;
    private String name;
    private Integer num;
    private String color;

    public Apple() {}
    
    public Apple(Integer id, String name, Integer num, String color) {
        this.id = id;
        this.name = name;
        this.num = num;
        this.color = color;
    }

    // 省略 setter、getter方法

    @Override
    public String toString() {
        return "Apple{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", num=" + num +
                ", color='" + color + '\'' +
                '}';
    }
}

数据

List<Apple> appleList = new ArrayList<>();

Apple apple1 =  new Apple(1,"苹果1",10, "red");
Apple apple2 = new Apple(1,"苹果2",20, "green");
Apple apple3 =  new Apple(2,"香蕉",30, "yellow");
Apple apple4 =  new Apple(3,"荔枝",40, "red");

appleList.add(apple1);
appleList.add(apple2);
appleList.add(apple3);
appleList.add(apple4);

常用收集器示例

  • toList
// 获取数量大于25的Apple
List<Apple> collect = appleList.stream()
                .filter(apple -> apple.getNum() > 25)
                .collect(toList());
//
[Apple{id=2, name='香蕉', num=30, color='yellow'}, 
 Apple{id=3, name='荔枝', num=40, color='red'}]
  • toSet
// 获取颜色信息
Set<String> collect = appleList.stream()
                .map(Apple::getColor)
                .collect(toSet());
// [red, green, yellow]
  • toCollection
List<Apple> collect = appleList.stream()
                .filter(x->x.getNum()>18)
                .collect(toCollection(ArrayList::new));
/-----------------------------/
[Apple{id=1, name='苹果2', num=20, color='green'}, 
 Apple{id=2, name='香蕉', num=30, color='yellow'}, 
 Apple{id=3, name='荔枝', num=40, color='red'}]
  • counting:统计数量
Long aLong = appleList.stream()
                .filter(x -> x.getNum() > 18)
                .collect(counting());
// 另一种写法
Long aLong = appleList.stream()
                .filter(x -> x.getNum() > 18)
                .count();
// 3
  • summingInt:对一个属性求和
Integer integer = appleList.stream()
                .collect(summingInt(p -> p.getNum()));
// 另一种写法
Integer integer = appleList.stream()
                .mapToInt(Apple::getNum).sum();
// 100
  • averagingInt:求平均值
Double aDouble = appleList.stream().collect(averagingInt(Apple::getNum));
// 25.0
  • summarizingInt:求最大、最小、平均值等
IntSummaryStatistics collect1 = appleList.stream().collect(summarizingInt(Apple::getNum));
// IntSummaryStatistics{count=4, sum=100, min=10, average=25.000000, max=40}
  • joining:对流中元素调用toString,拼接成字符串
String s = appleList.stream().map(Apple::getName).collect(joining("--"));
// 苹果1--苹果2--香蕉--荔枝
  • maxBy | minBy : 求最大最小元素
Optional<Apple> collect = appleList.stream()
                .collect(maxBy(comparing(Apple::getNum)));
// 另一种写法
Optional<Apple> collect = appleList.stream()
                .max(comparing(Apple::getNum))
// Apple{id=3, name='荔枝', num=40, color='red'}
  • reducing:规约操作
Integer integer = appleList.stream()
                .collect(reducing(0, Apple::getNum, Integer::sum));
// 另一种写法
Optional<Integer> reduce = appleList.stream()
                .map(Apple::getNum)
                .reduce(Integer::sum);
// 100
  • groupingBy | partitioningBy :分组操作
Map<Integer, List<Apple>> groupBy = appleList.stream()
                .collect(Collectors.groupingBy(Apple::getId));
// {
    1=[Apple{id=1, name='苹果1', num=10, color='red'}, 
     Apple{id=1, name='苹果2', num=20, color='green'}], 
  2=[Apple{id=2, name='香蕉', num=30, color='yellow'}], 
    3=[Apple{id=3, name='荔枝', num=40, color='red'}]}

// partitioningBy:条件分组
Map<Boolean, List<Apple>> collect1 = appleList.stream()
                    .collect(partitioningBy(x -> x.getNum() > 24));
// {
    false=[Apple{id=1, name='苹果1', num=10, color='red'}, 
         Apple{id=1, name='苹果2', num=20, color='green'}],
  true=[Apple{id=2, name='香蕉', num=30, color='yellow'}, 
        Apple{id=3, name='荔枝', num=40, color='red'}]}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值