一些Lambda表达式的学习
1. Collectors.toMap(Department::getId, Department::getName)这样是形成一个Map<Long, String>,Department的ID为值,Name为值
2. Collectors.toMap(Department::getId, Function.identity())这样是形成一个Map<Long, Department>,Department的ID为键,Department为值
3. 当要转化成一个Map的时候,怎么判断是用Collectors.toMap还是Collectors.groupingBy呢?很简单,如果Map的值是一个List就用groupingBy,如果不是List就用toMap
1 Map<Long, List<Animal>> id2AnimalsMap = animals.stream().collect(Collectors.groupingBy(Animal::getId())); 2 Map<Long, Animal> id2AnimalMap = animals.stream().collect(Collectors.toMap(Animal::getId(), Function.identity());
4. 用forEach来循环
1 for (Animal animal : animalList){ 2 /* 3 * process 4 * */ 5 }
可改写为
1 animalList.forEach(animal -> { 2 /* 3 * process 4 * */ 5 });
posted on 2019-11-11 10:52 MikeLin麦克林 阅读(145) 评论(0) 编辑 收藏 举报