List<User> users = new ArrayList<>();
users.add(new User(1,"小明",1));
users.add(new User(2,"小李",2));
users.add(new User(3,"小话",1));
users.add(new User(4,"小么",1));
users.add(new User(4,"小么",1));
//提出 id 字段 集合
List<Integer> collect = users.stream().map(User::getId).collect(Collectors.toList());
//取所有实体(Integer)id转换成long 集合
List<Long> collect0 = users.stream().map(i->i.getId().longValue()).collect(Collectors.toList());
//映射成 map<id,实体>
Map<Integer, User> collect1 = users.stream().collect(Collectors.toMap(User::getId, Function.identity()));
//映射成 map<id,姓名>
Map<Integer, String> collect2 = users.stream().collect(Collectors.toMap(User::getId, User::getName));
//映射成 map<姓名,id>
Map<String, Integer> collect3 = users.stream().collect(Collectors.toMap(User::getName, User::getId));
//以性别 分组
Map<Integer, List<User>> collect4 = users.stream().collect(Collectors.groupingBy(User::getSex));
//过滤 (id为偶数的 并且性别==1的)
List<User> collect5 = users.stream().filter(i -> i.getSex().equals(1) && i.getId() % 2 == 0).collect(Collectors.toList());
//去重复
List<User> collect6 = users.stream().distinct().collect(Collectors.toList());
//打印所有实体 (实体 实现toString)
users.stream().forEach(System.out::println);
网友评论