java8 stream 用法
1 private List<User> users = Arrays.asList( 2 new User("1001", "John", 16), 3 new User("1002", "Carly", 17), 4 new User("1003", "Tom", 11), 5 new User("1004", "Mike", 11)); 6 7 8 private void lambdaFunctions() { 9 10 // 转为某一属性的集合 11 List<String> names = users.stream().map(User::getName).collect(Collectors.toList()); 12 13 // 转为以某一属性为key,另一属性为value的map 14 Map<String, Integer> idAgeMap = users.stream().collect(Collectors.toMap(User::getId, User::getAge)); 15 16 // 转为以某一属性为key,对象本身为value的map 17 Map<String, User> idUserMap = users.stream().collect(Collectors.toMap(User::getId, User -> User)); 18 19 // 转为以某一属性为key,对象本身的集合为value 20 Map<String, List<User>> idUsersMap = users.stream().collect(Collectors.groupingBy(User::getId, Collectors.toList())); 21 22 // 过滤 23 List<User> users1 = users.stream().filter(user -> user.getAge() >= 16).collect(Collectors.toList()); 24 25 //过滤 26 List<User> users2 = users.stream().filter(user -> { 27 return user.getAge() < 16; 28 }).collect(Collectors.toList()); 29 30 31 // A对象集合转为B对象集合 32 List<Person> persons = users.stream().map(user -> { 33 return new Person(user.getId(), user.getName(), user.getAge()); 34 }).collect(Collectors.toList()); 35 36 37 }