Collections.toMap()方法使用
1)实体类:
@ToString
@Data
@AllArgsConstructor
public class People {
private Integer id;
private String name;
private String address;
private Integer age;
}
2)测试类
public static void main(String[] args) {
People people1 = new People(1, "only-qi1", "bbb", 11);
People people2 = new People(2, "only-qi2", "ccc", 12);
People people3 = new People(3, "only-qi3", "dddd", 13);
People people4 = new People(1, "only-qi4", "fff", 14);
People people5 = new People(2, "only-qi5", "eee", 15);
People people6 = new People(1, "only-qi6", "ttttt", 11);
ArrayList<People> arrayList = new ArrayList<>();
arrayList.add(people1);
arrayList.add(people2);
arrayList.add(people3);
arrayList.add(people4);
arrayList.add(people5);
arrayList.add(people6);
System.out.println("-----------------toMap()方法: 收集一下集合中每个对象的两个单独的属性---------------");
Map<String, String> collect = arrayList.stream().collect(Collectors.toMap(People::getName, People::getAddress));
for (String s : collect.keySet()) {
System.out.println("key值是:" + s + "=========" + "value的值是" + collect.get(s));
}
arrayList.stream().collect(Collectors.toMap(People::getName, p -> p));
System.out.println("-------------------toMap()方法:收集一下属性和对象本身----------------------");
Map<String, People> collect1 = arrayList.stream().collect(Collectors.toMap(People::getName, p -> p));
for (String s : collect1.keySet()) {
System.out.println("key值是:" + s + "=========" + "value的值是" + collect1.get(s));
}
}
注:
使用toMap()函数之后,返回的就是一个Map了,自然会需要key和value。
toMap()的第一个参数就是用来生成key值的,第二个参数就是用来生成value值的