Map<String,List<String>>map=list.stream().collect(Collectors.toMap(Person::getId,p->{List<String>getNameList=newArrayList<>();getNameList.add(p.getName());returngetNameList;},(List<String>value1,List<String>value2)->{value1.addAll(value2);returnvalue1;}));System.out.println(map); 输...
map.entrySet().stream().forEach(System.out::println);//转换为TreeMapMap<Integer, Person> treeMap = personList.stream().collect(Collectors.toMap(Person::getId, d->d, (oldValue, newValue)->newValue, TreeMap::new)); System.out.println("treeMap:==="); treeMap.entrySet().stream().for...
List<Student> students=Data.initData();// students.stream().map(student -> student.getName()).forEach(System.out::println);//将所有的学生姓名放到list中List<String> studentNames=students.stream().map(student -> student.getName()).collect(Collectors.toList());for(String studentName:studentN...
Map<Integer, String> collect1 = users.stream() .collect(Collectors.toMap(User::getId, User::getName)); System.out.println(collect1); // {1=Tom, 2=Jack, 3=Steve} } } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24...
// Stream操作 String name2 = properties.stream() .sorted(Comparator.comparingInt(x -> x.distance)) .findFirst() .get().name; System.out.println("距离我最近的店铺是:" + name); 1. 2. 3. 4. 5. 6. 新的API对所有的集合操作都提供了生成流操作的方法,写的代码也行云流水,我们非常简单的就...
Map<String, Integer> ageByName = people.stream() .collect(Collectors.toMap(Person::getName, Person::getAge)); System.out.println(ageByName); } } classPerson{ privateString name; privateintage; publicPerson(String name,intage){ this.name = name; ...
Map<Long,String>map=userList.stream().collect(Collectors.toMap(User::getId,User::getName)); 这个获取的就是key为id,value为name的map了。 2. 三个参数的用法 还是沿用上面那个例子,如果这个时候你想获取key是age,value是name的map呢?如果你还是沿用上面的方法,就会出问题了,因为有两个age...
Stream 我们使用了 Java 提供的 Stream,当然你也可以用 For 循环。 下面的 map1 和 map 2 是等价的。List<Integer> reqIds = Arrays.asList(1, 2); List<Integer> reqs = Arrays.asList(1); Map<Integer, Boolean> map1 = reqIds.stream().collect(Collectors...
stream().map(Person::getName) .collect(Collectors.toCollection(TreeSet::new)); // Convert elements to strings and concatenate them, separated by commas String joined = things.stream() .map(Object::toString) .collect(Collectors.joining(", ")); // Compute sum of salaries of employee int ...
在stream().map().collect(Collectors.toList()).forEach()中,你的forEach()针对的List;而 stream().map().forEach()针对的是Stream流。从结果操作来看是一样的,中间过程回产生一些临时变量。最