lamda 实战分组,过滤,去重,排序,Map

您所在的位置:网站首页 lambda分组排序最新 lamda 实战分组,过滤,去重,排序,Map

lamda 实战分组,过滤,去重,排序,Map

2023-12-12 11:22| 来源: 网络整理| 查看: 265

filter 过滤两个list List list1; List list2; // 交集(list1 - list2) List intersection = list1.stream() .filter(item -> list2.contains(item)) .collect(Collectors.toList()); System.out.println("---交集 intersection---"); intersection.parallelStream().forEach(System.out::println); // 差集 (list1 - list2) List reduce1 = list1 .stream() .filter(item -> !list2.contains(item)) .collect(Collectors.toList()); System.out.println("---差集 reduce1 (list1 - list2)---"); reduce1.parallelStream().forEach(System.out::println); // 差集 (list2 - list1) List reduce2 = list2 .stream() .filter(item -> !list1.contains(item)) .collect(Collectors.toList()); System.out.println("---差集 reduce2 (list2 - list1)---"); reduce2.parallelStream().forEach(System.out::println); anyMatch 判断是否有满足条件的 取出id相同的学生 List StudentList= new ArrayList(); List StudentList2= new ArrayList(); for (Student model : StudentList) { if (StudentList.stream().anyMatch(a -> a.equals(model.getId()))) { StudentList2.add(model); } } findFirst 获取数据流中的第一个元素 Entity entity = collect.stream().findFirst().get();

分组

// 进行分组 Map groupIdList = userMeunDto.getDtos().stream().collect(Collectors.groupingBy(UserPutDto::getType)); //判断是否存在key if (groupIdList.containsKey(1) list转map Map maps = userList.stream().collect(Collectors.toMap(User::getId,Function.identity())); 看来还是使用JDK 1.8方便一些。 二、 另外,转换成map的时候,可能出现key一样的情况,如果不指定一个覆盖规则,上面的代码是会报错的。转成map的时候,最好使用下面的方式: Map maps = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (key1, key2) -> key2)); 三、 有时候,希望得到的map的值不是对象,而是对象的某个属性,那么可以用下面的方式: Map maps = userList.stream().collect(Collectors.toMap(User::getId, User::getAge, (key1, key2) -> key2)); //排序根据VipCardVo类的getVipCardType进行排序 list=list.stream().sorted(Comparator.comparing(VipCardVo::getVipCardType)).collect(Collectors.toList()); //倒序 list.stream().sorted(Comparator.comparing(Dto::getStateCode).reversed()).collect(Collectors.toList()); List 去重 code = code.stream().distinct().collect(Collectors.toList()); //获取id 的集合 List LongList = logDOList.stream().map(CtripGoodsDO::getId).collect(Collectors.toList());

 String转Long

List=stringList.stream().map(Long::valueOf).collect(Collectors.toList());

Long转String

List=longList.stream().map(String::valueOf).collect(Collectors.toList());

对当前数组进行过滤removeIf

1.filter是对数组的过滤过滤之后返回一个对象本身用于聚合生成新的对象,并且它的判定方式是 false过滤,

2.removeIf和原先数组的remove如出一辙,都是直接对数组本身下手,对数组里的对象进行移除。参数为 true移除

collection.removeIf( person -> person.getAge() >= 30 );//过滤30岁以上的求职者

按照字段来进行list 分组

List ctripHotelMatchLists = ctripHotelDOList.stream().collect( Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet(Comparator.comparing(o -> o.getHotelCode()))), ArrayList::new));

按照list 进行排序

common.sort(Comparator.comparing(item -> channelCommon.indexOf(item.getChannelCode())));



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3