场景1:将一个包含person的list转成key是手机号,value是该person对象的map
场景2:将一个包含person的list转成key是性别,value是属于该性别的所有person姓名的map
// 假装使用了lombok
// Person实体
@Data
class Person {
private String name;
private String phone;
private String gender;
}
public static void main() {
// 存储person的list
private List<Person> personList = new ArrayList<Person>();
personList.add(new Person("zhangsan", "18912345667", "Male"));
personList.add(new Person("lisi", "16712345667", "Male"));
personList.add(new Person("susan", "13112345667", "Female"));
personList.add(new Person("marry", "15612345667","Female"));
Map<String, Person> map1 = new HashMap<String, Person>();
Map<String, String> map2 = new HashMap<String, Person>();
// 场景1:java8之前使用循环
for (Person person : personList) {
// 因为手机号的唯一性,所以没有考虑key冲突的情况。
map1.put(person.getPhone(), person);
}
// 场景1:使用java8的流
map1 = personList.stream().collect(Collectors.toMap(Person::getPhone, Function.identity()));
// 场景2:java8之前使用循环
for (Person person : personList) {
String key = person.getGender();
String value = person.getName();
if (map2.containsKey(key)) {
value = map2.get(key) + "," + value;
}
map2.put(key, value);
}
// 场景2:使用java8的流,但是有多个value对应1个key的情况
// toMap的第三个参数是merge规则
map2 = personList.stream().collect(Collectors.toMap(Person::getPhone, Function.identity()), (oldV, newV) -> oldV + "," + newV);
}
网友评论