java stream流处理技巧汇总

Map 遍历

map对象使用stream来进行操作。

map.entrySet().stream().map(Map.Entry::getValue)

stream引用

	    Box one = new Box();
        one.setId(1);
        one.setName("one");
        Box two = new Box();
        two.setId(2);
        two.setName("two");

        Box thr = new Box();
        thr.setId(3);
        thr.setName("thr");

        List<Box> boxList = Lists.newArrayList();
        boxList.add(one);
        boxList.add(two);
        boxList.add(thr);

        int id = 2;
        List<Box> filterBoxList = boxList.stream().filter(b->b.getId()==id).collect(Collectors.toList());

        two.setId(3);
        System.out.println(FastJsonUtil.toJSONString(filterBoxList));

list转string,每一个用逗号隔开

idSet.stream().map(g->String.valueOf(g)).collect(Collectors.joining(","))

list去重

这里的去重是简单的去重,主要针对字符串、基本类型等,如果是自定义的对象,可能效果没有那么好,要改写hashcode()方法等。

	    List<Long> idList = Lists.newArrayList();
        idList.add(1l);
        idList.add(2l);
        idList.add(3l);
        idList.add(3l);
        idList.add(3l);
        idList.add(3l);
        idList.add(3l);

        idList = idList.stream().distinct().collect(Collectors.toList());

list 自定义对象类 字段去重

如果自己定义了一个对象,想对这个对象里的集合元素进行去重,按照某个字段来去重,这就有点复杂了,这样操作就可以了。

import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;
 
// 根据id去重
     List<Person> unique = appleList.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(comparingLong(Apple::getId))), ArrayList::new)
        );

求集合中min、sum、max等值

通过reduce方法来实现,举个例子如下:

Stream<String> stream = Stream.of("I", "love", "you", "too");
Optional<String> longest = stream.reduce((s1, s2) -> s1.length()>=s2.length() ? s1 : s2);

通过reduce方法来得到最小长度的字符串,你也可以更改里面的代码来实现其他逻辑。

参考博客

Java8新特性学习-Stream的Reduce及Collect方法详解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值