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

目录

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

一、排序

1、正序

List newvos = vos.stream().sorted(Comparator.comparing(UserVO::getTime)).collect(Collectors.toList());

2、逆序

List newvos = vos.stream().sorted(Comparator.comparing(UserVO::getTime).reversed()).collect(Collectors.toList());

3、根据某个属性或多个属性排序

多个属性排序:需要添加排序条件就在后面添加.thenComparing(UserVO::getxxx),它是在上一个条件的基础上进行排序

List list10 = listTemp.stream().sorted(Comparator.comparing(UserVO::getNum)
                    .thenComparing(UserVO::getName);
                    

二、去重

1、去重

List newvos = vos.stream().distinct().collect(Collectors.toList());

2、根据某个属性去重(它将该字段还进行排序了)

List 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 newvos= result.stream().filter(distinctByKey(o -> o.getId())).collect(Collectors.toList());


public static  Predicate distinctByKey(Function keyExtractor) {
     Map map = new HashMap();
     return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}

4、对多个对象去重(它将该字段还进行排序了)

List newvos = list.stream().collect( Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet(Comparator.comparing(o->o.getID()+ ";" + o.getName()))),ArrayList::new)); 

三、分组

1、单条件分组

Map<String, List> groupedMap = result.stream().collect(Collectors.groupingBy(dto -> dto.getId()));
// 提取分组后的列表
List<List> resultLists = new ArrayList(groupedMap.values());
for (List resultList : resultLists) {
	//方法体
}

2、多条件分组

在groupingBy里面添加分组条件(dto -> dto.getId() +“|” +dto.getName())

四、过滤

1、在集合中查询用户名user为lkm的集合

List newvos = vos.stream().filter(o ->"lkm".equals(o.getName())).collect(Collectors.toList());

2、在集合中不要用户名user为lkm的集合(true是要,false是不要)

		List newVos = vos.stream().filter(o ->{
			if("lkm".equals(o.getName())){
				return false;
			}else{
				return true;
			}
		}).collect(Collectors.toList());

五、合并

1、合并集合某个属性

List 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 sublist = list.stream().limit(n).collect(Collectors.toList());

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/94776c1b0e.html