1、List转Map
// 通过用户年龄分组
List<User> users 通过对象内字段转换为Map<String, List<User>
Map<Integer, List<User>> collect = users.stream().collect(groupingBy(User::getAge));
2、List转Map
//List<User> users 通过对象内字段转换为Map<Long,User>
users .stream().collect(Collectors.toMap(User::getUserId, User-> User));
3、通过某个对象内元素去重
//List<User> users 通过对象内字段去重
users = users .stream().collect(
collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(User::getName))),
ArrayList::new));
4、集合过滤去重
// List<User> users 按照规则过滤,去重
users.stream().filter(user-> {
if (user.getName() == null) {
return false;
} else if (StringUtils.isNotEmpty(user.getInfo())) {
return false;
} else {
return true;
}
}).distinct().collect(Collectors.toList());
5、获取List中的List
List<School> schools = new ArrayList<>;
// 每个school中包含List<User> users
// 将全部users抽出
Set<User> users= schools .stream().flatMap(school -> school.getUsers().stream()).collect(Collectors.toSet());
6、根据list中属排序
list= list.stream() .sorted(Comparator.comparing(User::getBirthday)
.reversed()).collect(Collectors.toList());
做项目遇到的问题,持续更新