這應該工作:
Map<String, Integer> map = animal.stream().collect(
Collectors.groupingBy(
Animal::getName,
Collectors.collectingAndThen(
Collectors.mapping(Animal::getColor, Collectors.toSet()),
Set::size)
)
);
這裏一些測試代碼:
public static void main(String[] args) {
List<Animal> animal = new ArrayList<>();
animal.add(new Animal("Dog","black"));
animal.add(new Animal("Dog","black"));
animal.add(new Animal("Dog","blue"));
animal.add(new Animal("Cat","blue"));
animal.add(new Animal("Cat","white"));
Map<String, Integer> map = animal.stream().collect(
Collectors.groupingBy(
Animal::getName,
Collectors.collectingAndThen(
Collectors.mapping(Animal::getColor, Collectors.toSet()),
Set::size)
)
);
for(Entry<String, Integer> entry:map.entrySet()) {
System.out.println(entry.getKey()+ " : "+entry.getValue());
}
}
給出
Cat : 2
Dog : 2
注:這個答案的靈感來自於該SO後:https://stackoverflow.com/a/30282943/1138523
你可以,如果你願意,使用地圖::針對的forEach測試代碼:map.forEach((鍵,值) - > System.out中。 println(key +「:」+ value)); – srborlongan
謝謝,不知道 –