List<StudentDTO> studentDTOS = Lists.newArrayList();
studentDTOS.add(new StudentDTO(1,"xixi"));
studentDTOS.add(new StudentDTO(2,"houhou"));
studentDTOS.add(new StudentDTO(3,"maomi"));
Map<Integer, String> collect = studentDTOS.stream().collect(
Collectors.toMap(StudentDTO::getStudentId, StudentDTO::getStudentName));
System.out.println(JSON.toJSON(collect)); // {"1":"xixi","2":"houhou","3":"maomi"}
public void streamToMap1() {
List<StudentDTO> studentDTOS = Lists.newArrayList();
studentDTOS.add(new StudentDTO(1,"xixi"));
studentDTOS.add(new StudentDTO(1,"houhou"));
studentDTOS.add(new StudentDTO(3,"maomi"));
Map<Integer, String> collect = studentDTOS.stream()
.collect(Collectors.toMap(StudentDTO::getStudentId, StudentDTO::getStudentName));
System.out.println(JSON.toJSON(collect));
}
studentDTOS.stream().collect(Collectors.toMap(StudentDTO::getStudentId,
StudentDTO::getStudentName,(oldValue, newValue) -> newValue));
{"1":"houhou","3":"maomi"}
studentDTOS.stream().collect(Collectors.toMap(StudentDTO::getStudentId,
StudentDTO::getStudentName,(oldValue, newValue) -> oldValue + "," + newValue));
{"1":"xixi,houhou","3":"maomi"}
public void streamToMap2() {
List<StudentDTO> studentDTOS = Lists.newArrayList();
studentDTOS.add(new StudentDTO(1,"xixi"));
studentDTOS.add(new StudentDTO(2,"houhou"));
studentDTOS.add(new StudentDTO(3,null));
Map<Integer, String> collect = studentDTOS.stream().collect(Collectors
.toMap(StudentDTO::getStudentId, StudentDTO::getStudentName));
System.out.println(JSON.toJSON(collect));
}
studentDTOS.stream().collect(Collectors.toMap(StudentDTO::getStudentId, studentDTO
-> studentDTO.getStudentName()==null?"":studentDTO.getStudentName()));
输出结果:
{"1":"xixi","2":"houhou","3":""}
collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner)
方法构建Map<Integer, String> collect = studentDTOS.stream().collect(HashMap::new,
(n, v) -> n.put(v.getStudentId(), v.getStudentName()), HashMap::putAll);
for(Map.Entry<Integer, String> entry:collect.entrySet()){
System.out.println(entry.getKey()+"="+entry.getValue());
}
1=xixi
2=houhou
3=null
Map<Integer, Optional<String>> collect = studentDTOS.stream().collect(Collectors
.toMap(StudentDTO::getStudentId,
studentDTO -> Optional.ofNullable(studentDTO.getStudentName())));
for(Map.Entry<Integer, Optional<String>> entry:collect.entrySet()){
System.out.println(entry.getKey()+"="+entry.getValue().orElse(""));
}
1=xixi
2=houhou
3=