java stream分组操作使用的是 Collectors.groupingBy
定义一些实体类;
publicclassAnimal { privateStringname; privatedoubleweight; publicAnimal(Stringname, doubleweight) { this.name=name; this.weight=weight; } publicStringgetName() { returnname; } publicdoublegetWeight() { returnweight; } } publicclassCatextendsAnimal { publicCat(Stringname, doubleweight) { super(name, weight); } } publicclassDogextendsAnimal { publicDog(Stringname, doubleweight) { super(name, weight); } }
求一个动物列表中不同动物的平均体重:
publicclassTest { publicstaticvoidmain(String[] args) { List<Animal>data=Arrays.asList( newCat("cat1", 22.2d), newCat("cat22", 10.1d), newDog("dog1", 30d), newDog("dog2", 35d) ); Map<?extendsClass<?extendsAnimal>, Double>collect=data.stream() .collect(Collectors.groupingBy(Animal::getClass, Collectors.averagingDouble(Animal::getWeight))); collect.forEach((k, v) -> { System.out.println(k.getName() +" average weight: "+v); }); } }
输出: