大家好,欢迎来到IT知识分享网。
一、排序
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());
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/112559.html