Java8常用的集合操作

Java8常用的集合操作

说明 objList:List的集合,StudentInfo:学生的实体类,strList:List集合类

1、选出更新时间最新的记录的Id

Long id = byCrmChance.stream().max(Comparator.comparing(CrmChanceAudit::getUpdateTime))
		.orElse(new CrmChanceAudit()).getId();

2、使用指定的符号来连接集合中的元素

String resultStr = String.join(",", strList)

3、按照年龄升序排序

objList = objList.stream().sorted(Comparator.comparing(StudentInfo::getAge)).collect(Collectors.toList());

4、按照年龄降序排序

objList = objList.stream().sorted(Comparator.comparing(StudentInfo::getAge).reversed()).collect(Collectors.toList());

5、按下标遍历数组元素

Stream.iterate(0, i -> i + 1).limit(objList.size()).forEach(i -> {
	System.out.println(objList.get(i));
});

6、获取最新的数据

StudentInfo s = objList.stream().max(Comparator.comparingLong(a -> a.getCreateTime().getTime())).orElse(null);

7、List转Map

Map<Long, StudentInfo> map = objList.stream().collect(Collectors.toMap(StudentInfo::getId, Function.identity(), (key1, key2) -> key2))

8、List对某个属性进行分组

Map<Long, List<StudentInfo>> map = objList.stream().collect(Collectors.groupingBy(StudentInfo::getGrade));

9、对list进行先分组再对Map中的value进行类型转换

Map<Long, List<Long>> map = serviceType.stream().collect(Collectors.groupingBy(EnterpriseModel::getId))
		.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, v -> 
			v.getValue().stream().map(EnterpriseModel::getServiceTypeId).collect(Collectors.toList())));

10、去除List中的null元素

	list.removeAll(Collections.singleton(null));
posted @ 2021-06-16 09:56  Aj小菜  阅读(332)  评论(0编辑  收藏  举报