使用Java 8流收集重复项

时间:2016-07-26 11:57:07

标签: java lambda java-8

我有cats的列表,我希望将colourowner分组,然后按public class Cat{ private String name; private Owner owner; private String color; public Cat(String name,Owner owner,String color){ this.name=name; this.owner= owner; this.color= color; } } public class Owner{ private String name; public Owner(String name){ this.name= name; } } 对其进行分组。我如何在Java 8中执行此操作?

Owner owner1= new Owner("John");  Owner owner2= new Owner("Smith");
Owner owner3= new Owner("Scott"); 
Cat cat1 = new Cat ("Cat1",owner1,"Brown"); 
Cat cat2 = new Cat ("Cat2",owner2,"Black");
Cat cat3 = new Cat ("Cat3",owner1,"Brown");
Cat cat4 = new Cat ("Cat4",owner3,"White");

List<Cat> catList = new ArrayList<>();
catList.add(cat1);
catList.add(cat2);
catList.add(cat3);
catList.add(cat4);

假设我有以下数据:

owner1

我期待owner2有两只猫的地图,owner3有1只,email有一只猫。

1 个答案:

答案 0 :(得分:4)

使用Collectors.groupingBy和适当的getter方法:

Map<Owner, List<Cat>> byOwner = catList.stream()
        .collect(Collectors.groupingBy(Cat::getOwner));
// {Owner(name=John)=[Cat(name=Cat1), Cat(name=Cat3)], Owner(name=Scott)=[Cat(name=Cat4)], Owner(name=Smith)=[Cat(name=Cat2)]}

Map<String, List<Cat>> byColor = catList.stream()
        .collect(Collectors.groupingBy(Cat::getColor));
// {Brown=[Cat(name=Cat1), Cat(name=Cat3)], White=[Cat(name=Cat4)], Black=[Cat(name=Cat2)]}