2019.01.16
1.遍历list
List<User> userList = lists.newArrayList();
User user1 = new User(1L,"zhangsan",24);
User user2 = new User(2L,"zhangsan2",25);
userList.add(user1);
userList.add(user2);
userList.stream().forEach(user -> {
System.out.println(user.getName());
});
2.list转为Map(
* List -> Map
* 需要注意的是:
* toMap 如果集合对象有重复的key,会报错Duplicate key ....
* apple1,apple12的id都为1。
* 可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2)
Map<Long,User> userMap = userList.stream().collect(Collectors.toMap(User::getId,a->a,(k1,k2)->k1));
3.list里面的对象元素以其中某个元素分组
Map<String,List<User>> groupBy = userList.stream().collect(Collectors.groupingBy(User::getName));
4.过滤:从集合中过滤出符合条件的元素
List<User> filterList = userList.stream().filter(user -> user.getName().equals("zhangsan")).collect(Collectors.toList());
filterList.Stream().forEach(user -> {
System.out.println(user.getName());
});
5.求和:将集合中的数据按照某个属性求和
int totalAge = userList.stream().mapToInt(User::getAge).sum();
附加:找到第一个分数高于90的
void doSomeThing(List<Student> list) {
Optional<Student> optionalStudent = list.stream().filter(item -> item.getScore() > 90).findFirst();
optionalStudent.ifPresent(student -> System.out.println(student.getName()));
}