stream流各种操作(笔记)

        1、字符串转数组

List<String> collect = Arrays.stream(str.split(",")).collect(Collectors.toList());

2、两个集合的交集

List<String> collect = oldArray.stream()
                .filter(old ->
                        newArray.stream().anyMatch(old::equals)
                ).collect(Collectors.toList());

3、获取第一个集合存在 ;第二个集合却不存在的元素

List<String> collect = oldArray.stream()
                .filter(old ->
                        newArray.stream().noneMatch(old::equals)
                ).collect(Collectors.toList());

或者...

List<String> collect = oldArray.stream()
                .filter(old ->
                        !newArray.contains(old)
                ).collect(Collectors.toList());

 再或者...

List<String> collect = oldArray.stream()
                .filter(old ->
                        newArray.stream().noneMatch(ss -> Objects.equals(old, ss))
                ).collect(Collectors.toList());

  


4、去重

普通去重...

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

 根据对象字段去重...

list.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(
                        () -> new TreeSet<>(Comparator.comparing(Test::getId))
                ), ArrayList::new)
        );

 5、过滤并去重

list.stream()
                // 过滤
                .filter(item -> item.equals("11"))
                // 去重
                .distinct()
                .collect(Collectors.toList());

6、 多条件过滤


7、合并两个list并去重


 8、替代嵌套循环


9、字符串转集合并转换类型


10、 排序

普通排序...

根据对象属性排序...


11、 List<List<T>>  转为  List<T>


12、多个字符串转为集合 并合并成一个List 

list = [ "1,2" , "3,4,5,6" ] 转为 list = [ 1, 2, 3, 4, 5, 6 ] 


 13、List转Map

或...


14、 两个list根据属性合并

或者... 


15、用流来分页


16、分组

 嵌套分组


17、 先分组,再对分组里的集合经行判断,返回分组的key以及判断的结果


18、根据List中的对象中的List的值来分组

对象:

实现:

 效果:

Map<String, List<Test>> test = list.stream()
                // 过滤掉 type 为空的对象
                .filter(p -> !CollectionUtils.isEmpty(p.getType()))
                // 将每个 Test 拆分成多个键值对,其中键为 type,值为 Test 对象
                .flatMap(p -> p.getType().stream()
                        .map(type -> new AbstractMap.SimpleEntry<>(type, p)))
                // 将拆分后的键值对按照键分组,并将每个键对应的值放入一个列表中
                .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey,
                        // 创建一个只包含当前值的列表
                        e -> new ArrayList<>(Collections.singletonList(e.getValue())),
                        // 合并两个值(即两个列表)为一个列表
                        (l1, l2) -> {
                            l1.addAll(l2);
                            return l1;
                        }));

19.根据list中某个字段去重后并拼接

 

 

随手笔记

未完待续。。。。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值