Java 8 Collectors分组及Collectors.mapping使用案例
今天学习的考核中,导师给出了一个需求:
利用java8 lambdas语言特性处理如下java集合对象,
为了方便描述对象用json表示为[{id:1,name:null},{id:1,name:”liwei”},{id:2,name:”zhansan”},{id:2,name:”lisi”}]
期望处理后的集合对象为[{id:1,name:[liwei]},{id:2, name:[zhansan,lisi] }]
最开始拿到需求的时候想了很久都没做出来,使用Collectors分组时也只实现了对id或name的分组,并未考虑到对两个都进行分组。咨询了做了一年多开发的同学才帮我正确解答。
具体代码实现如下:
//创建Person实体类:
public class Person {
private Integer id;
private String name;
public Person(Integer id) {
this.id = id;
}
public Person() {
}
public Person(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
创建接收处理后的对象类:
public class PersonV2s {
private Integer id;
private List<String> names;
public PersonV2s(Integer id, List<String> names) {
this.id = id;
this.names = names;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<String> getNames() {
return names;
}
public void setNames(List<String> names) {
this.names = names;
}
}
利用lambda进行数据处理
public class LambdaDemo2 {
@Test
public void test() {
List<Person> personList = Arrays.asList(
new Person(1),
new Person(1, "liwei"),
new Person(2, "zhansan"),
new Person(2, "lisi")
);
final Map<Integer, List<String>> map
= personList.stream().collect(Collectors.groupingBy(Person::getId, Collectors.mapping(Person::getName, Collectors.toList())));
final List<PersonV2s> personV2ss
= map.entrySet().stream().map(p -> new PersonV2s(p.getKey(), p.getValue().stream().filter(Objects::nonNull).collect(Collectors.toList()))).collect(Collectors.toList());
System.out.println(personV2ss.toString());
}
}