这种转换帮助我们更加方便的实现集合的整理,我也是在日常工作中遇到的,如果对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);
}
}
例如上面这样,这样功能就实现了