一、排序
1、正序
List<UserVO> newvos = vos.stream().sorted(Comparator.comparing(UserVO::getTime)).collect(Collectors.toList());
2、逆序
List<UserVO> newvos = vos.stream().sorted(Comparator.comparing(UserVO::getTime).reversed()).collect(Collectors.toList());
3、根据某个属性或多个属性排序
多个属性排序:需要添加排序条件就在后面添加.thenComparing(UserVO::getxxx),它是在上一个条件的基础上进行排序
List<UserVO> list10 = listTemp.stream().sorted(Comparator.comparing(UserVO::getNum) .thenComparing(UserVO::getName);
注意:如果排序的字段为空,以上方法会出现空指针异常!
解决方法:
List<UserVO> newvos = vos.stream().sorted(Comparator.comparing(UserVO::getTime,Comparator.nullsFirst(String::compareTo))).collect(Collectors.toList());
Comparator.nullsFirst(根据getTime类型改变::compareTo)
二、去重
1、去重
List<UserVO> newvos = vos.stream().distinct().collect(Collectors.toList());
2、根据某个属性去重(它将该字段还进行排序了)
List<UserVO> newvos = vos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->new TreeSet<>(Comparator.comparing(UserVO::getId))), ArrayList::new));
3、根据某个属性去重(这个方法没有排序)
import java.util.function.Function; import java.util.function.Predicate; List<UserVO> newvos= result.stream().filter(distinctByKey(o -> o.getId())).collect(Collectors.toList()); public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> map = new HashMap<>(); return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; }
4、对多个对象去重(它将该字段还进行排序了)
List<UserVO> newvos = list.stream().collect( Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o->o.getID()+ ";" + o.getName()))),ArrayList::new));
三、分组
1、单条件分组
Map<String, List<UserVO>> groupedMap = result.stream().collect(Collectors.groupingBy(dto -> dto.getId())); // 提取分组后的列表 List<List<UserVO>> resultLists = new ArrayList<>(groupedMap.values()); for (List<UserVO> resultList : resultLists) {
//方法体 }
2、多条件分组
在groupingBy里面添加分组条件(dto -> dto.getId() +“|” +dto.getName())
四、过滤
1、在集合中查询用户名user为lkm的集合
List<UserVO> newvos = vos.stream().filter(o ->"lkm".equals(o.getName())).collect(Collectors.toList());
2、在集合中不要用户名user为lkm的集合(true是要,false是不要)
List<UserVO> newVos = vos.stream().filter(o ->{
if("lkm".equals(o.getName())){
return false; }else{
return true; } }).collect(Collectors.toList());
五、合并
1、合并集合某个属性
List<UserVO> newvos = list.stream().collect(Collectors.toMap(BillsNums::getId, a -> a, (o1,o2)-> {
o1.setNums(o1.getNums() + o2.getNums()); o1.setSums(o1.getSums() + o2.getSums()); return o1; })).values().stream().collect(Collectors.toList());
六、截取
集合截取有两种方法,分别是list.subList(0, n)和Stream处理,前者集合如果不足n条,会出现异常错误,而后者截取前n条数据,哪怕集合不足n条数据也不会报错。
List<String> sublist = list.stream().limit(n).collect(Collectors.toList()); 今天的文章
Java 1.8 List集合排序、去重、分组、过滤、合并、截取操作分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ji-chu/3933.html