本帖最后由 gdlove 于 2020-10-12 13:39 编辑
1. 先定义公共list
List<User> userList = Arrays.asList(new User(1, 1, "张三"),
new User(2, 1, "李四"),
new User(3, 2, "王五"));
List<User> userList = new ArrayList<>(userList1);
2.最常用的循环 forEach
-
forEach userList,forEach(user ->{
//循环取值
//return 只是跳出本次循环和for循环的continue 一样效果
}); -
循环删除 Iterator it = userList.iterator();
while (it.hasNext()) {
User user = (User) it.next();
if (2 == user.getId()){
continue
}
it.remove();
}
3.list转map toMap
- 二选一即可
Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
Map<Integer, User> userMap1 = userList.stream().collect(Collectors.toMap(User::getId, user -> user)); 2.取对象的属性值 Map<Integer, Integer> typeMap = userList.stream().collect(Collectors.toMap(User::getId, User::getType)); 4.分组 groupingBy //对象分组
Map<Integer, List<User>> map = userList.stream().collect(Collectors.groupingBy(User::getType));
//对象属性分组
Map<Integer, List<String>> map2 =userList.stream().collect(Collectors.groupingBy(User::getType, Collectors.mapping(User::getTname, Collectors.toList()))); 5.排序 sorted
List<User> userListSortId = userList.stream().sorted(Comparator.comparing(User::getId)).collect(Collectors.toList());
List<User> userListSortId1 = userList.stream().sorted(Comparator.comparing(User::getId).reversed()).collect(Collectors.toList());
6.List属性判断 anyMatch、allMatch、noneMatch
boolean flag = userList.stream().anyMatch(user -> {
return user.getId() == 1;
});
boolean flag1 = userList.stream().allMatch(user -> {
return user.getId() == 1;
});
|
boolean flag2 = userList.stream().noneMatch(user -> {
return user.getId() == 1;
});