这种转换帮助我们更加方便的实现集合的整理,我也是在日常工作中遇到的,如果对Stream使用感兴趣的话可以可以关注一下,一起学习; 主要实现就是按照一个类的属性为key,然后把另一个属性作为Value值并且封装为List
public class TestDemo {
private static final Pattern DELIMITER = Pattern.compile(":");
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
Student student = new Student("张飞", 15, "郑州");
Student student1 = new Student("晨晨", 16, "开封");
Student student2 = new Student("春春", 17, "北京");
Student student3 = new Student("春春", 17, "日本");
students.add(student);
students.add(student1);
students.add(student2);
students.add(student3);
Map<String, Set<String>> map= students.stream().collect(Collectors.groupingBy(Student::getName,Collectors.mapping(Student::getAddress,Collectors.toSet())));
System.out.println(map);
}
}
例如上面这样,这样功能就实现了
本文介绍了一种将List转换为Map的实用方法,具体为:以一个类的特定属性作为Key,另一个属性的值集合作为Value,封装为List。通过Java Stream API的collect方法结合groupingBy、mapping和toSet收集器实现这一转换。

2万+

被折叠的 条评论
为什么被折叠?



