《Java8实战》05 - Stream流的Collectors实现: 将POJO实体列表转为<Id, POJO>的Map 或者 <Id, 某个属性> 一对一的KV键值对
笔记简记
- Collectors.groupingBy 简单使用
- Collectors.toMap 简单使用
数据准备 POJO测试类
@Data
class InnerClass {
private Long id;
private String name;
private LocalDateTime birthDay;
public InnerClass() {
}
InnerClass(Long id, String name, LocalDateTime desc) {
this.id = id;
this.name = name;
this.birthDay = desc;
}
}
实现<Id, POJO>的一对一Map代码及实现
InnerClass clazz1 = new InnerClass(1L, "name1", LocalDateTime.now());
InnerClass clazz2 = new InnerClass(2L, "name2", LocalDateTime.now().minusYears(1));
InnerClass clazz3 = new InnerClass(3L, "name3", LocalDateTime.now().minusYears(2));
ArrayList<InnerClass> allList = new ArrayList<>();
allList.add(clazz1);
allList.add(clazz2);
allList.add(clazz3);
// (Collectors.groupingBy() 的最简单的默认接口实现
// public static <T, K> Collector<T, ?, Map<K, List<T>>>
// groupingBy(Function<? super T, ? extends K> classifier) {
// return groupingBy(classifier, toList());
// }
Map<Long, List<InnerClass>> collect = allList.stream().collect(Collectors.groupingBy(InnerClass::getId));
collect.forEach((k, v) -> {
System.out.println("<Id, 对实体> " + k + " " + v);
});
// 生成<Id, 对实体>的Map 打印如下::::::::::::::::::::::::
//1 [InnerClass{id=1, name='name1', birthDay=2020-06-12T16:17:54.150}]
//2 [InnerClass{id=2, name='name2', birthDay=2019-06-12T16:17:54.151}]
//3 [InnerClass{id=3, name='name3', birthDay=2018-06-12T16:17:54.151}]
<Id, 某个属性> 一对一的KV键值对
/**
* 创建<Id, name> 一对一的KV键值对list
*/
Map<Long, String> longStringMap = allList.stream().collect(Collectors.toMap(InnerClass::getId, InnerClass::getName));
longStringMap.forEach((k, v) -> {
System.out.println("<Id, name>\t" + k + " " + v);
});
//<Id, name> 1 name1
//<Id, name> 2 name2
//<Id, name> 3 name3
创建<Id, List > 一对多的KV键值对list
/**
* 创建<Id, List<name> > 一对多的KV键值对list
*/
InnerClass clazz22 = new InnerClass(2L, "name222", LocalDateTime.now().minusYears(1));
InnerClass clazz33 = new InnerClass(3L, "name333", LocalDateTime.now().minusYears(2));
allList.add(clazz22);
allList.add(clazz33);
Map<Long, List<InnerClass>> collect1 = allList.stream().collect(Collectors.groupingBy(InnerClass::getId));
collect1.forEach((k, v) -> {
System.out.println("<Id, List<实体> > " + k + " " + v);
});
// 打印如下::::::::::::::::::::::::
//<Id, List<实体> > 1 [InnerClass{id=1, name='name1', birthDay=2020-06-12T16:48:29.381}]
//<Id, List<实体> > 2 [InnerClass{id=2, name='name2', birthDay=2019-06-12T16:48:29.382}, InnerClass{id=2, name='name222', birthDay=2019-06-12T16:48:29.404}]
//<Id, List<实体> > 3 [InnerClass{id=3, name='name3', birthDay=2018-06-12T16:48:29.382}, InnerClass{id=3, name='name333', birthDay=2018-06-12T16:48:29.404}]
你不逼自己一把,你永远都不知道自己有多优秀!只有经历了一些事,你才会懂得好好珍惜眼前的时光!