java8 日常使用
1、Collectors.toMap()
toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction, Supplier mapSupplier)
public static void main(String[] args) {
Student student = new Student().setId(2).setName("zs").setScore(20);
Student student2 = new Student().setId(1).setName("lisi").setScore(30);
List<Student> list = new ArrayList<>();
list.add(student);
list.add(student2);
/**
Collectors.toMap 方法参数参数1key的处理策略,参数2value的处理策略,参数3当key冲突时候处理的策略,参数4返回何种Map
注意点 1、key的重复时候处理
2、转map的出现值的空指针异常
*/
//转映射map
Map<String, Integer> map =
list.stream().collect(Collectors.toMap(Student::getName, Student::getScore));
list.stream().collect(Collectors.toMap(Student::getName, o->o.getScore()));
//处理值空指针
list.stream().collect(Collectors.toMap(Student::getName, o->Optional.ofNullable(o.getScore()).orElse(0)));
list.stream().collect(Collectors.toMap(Student::getName, o->Optional.ofNullable(o.getScore()).orElse(0),(v1,v2)->v1));
// 当key没有重复时候
Map<Integer, Student> map1 =
list.stream().collect(Collectors.toMap(Student::getId, o -> o));
// 或者
list.stream().collect(Collectors.toMap(Student::getId, Function.identity()));
list.add(student);
// 当key重复时候
list.stream().collect(Collectors.toMap(Student::getId, Function.identity(), (v1, v2) -> v1, TreeMap::new));
list.stream().collect(Collectors.toMap(Student::getId, Function.identity(), (v1, v2) -> v1, LinkedHashMap::new));
list.stream().collect(Collectors.toMap(Student::getId, Function.identity(), (v1, v2) -> v1, ConcurrentHashMap::new));
//参数3策略key重复时候进行的合并策略
list.stream().collect(Collectors.toMap(Student::getName, Function.identity(), Student::getMerge, TreeMap::new));
}
@Data
@Accessors(chain = true)
static class Student {
private Integer id;
private String name;
private Integer score;
public static Student getMerge(Student s1, Student s2){
s1.setScore(s1.getScore()+s2.getScore());
return s1;
}
}