class Person {
private String sex;
private List<String> nameList;
public Person(String sex, String name) {
this.sex = sex;
this.nameList = new ArrayList<>();
this.nameList.add(name);
}
public Person(String sex, List<String> nameList) {
this.sex = sex;
this.nameList = nameList;
}
}
public static void main(String[] args) {
Person p1 = new Person("M", "name1");
Person p2 = new Person("M", "name2");
Person p3 = new Person("F", "name3");
Person p4 = new Person("F", "name4");
Person p5 = new Person("F", "name5");
List<Person> ps = Arrays.asList(p1, p2, p3, p4, p5);
// sex --> Person
Map<String, Person> map1 = new HashMap<>();
ps.forEach(p -> {
Person pp = map1.get(p.getSex());
if (pp == null) {
pp = new Person(p.getSex(), p.getNameList());
map1.put(p.getSex(), pp);
} else {
pp.getNameList().addAll(p.getNameList());
}
});
System.out.println(map1);
Map<String, Person> map2 = ps.stream().collect(/* how to write here*/);
System.err.println(map2);
}
我希望用户ps.stream().collect()
解决此问题,例如主()
谢谢!
答案 0 :(得分:0)
创建人物姓名(键)到人物(值)的地图
Collectors.toMap(p -> p.getName(), p -> p);
答案 1 :(得分:0)
我知道答案;
product category