Java 1.8 List集合排序、去重、分组、过滤、合并、截取操作

目录

    • 一、排序
    • 二、去重
    • 三、分组
    • 四、过滤
    • 五、合并
    • 六、截取

一、排序

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);
                    

二、去重

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://blog.csdn.net/lkm987654321/article/details/131438990

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2024年1月8日
下一篇 2024年1月8日

相关推荐