public class Person {
private String name;
private Color favouriteColor;
}
public enum Color {GREEN, YELLOW, BLUE, RED, ORANGE, PURPLE}
使用Java8流API有一個List<Person>
我可以trasform它在一個Map<Color, Long>
具有每Color
的計數,也可用於不屬於色列入清單。 例子:
List<Person> list = List.of(
new Person("Karl", Color.RED),
new Person("Greg", Color.BLUE),
new Person("Andrew", Color.GREEN)
);
Trasforming這個名單在地圖與所有與他們的計數枚舉的顏色。
感謝
解決
使用自定義收集解決:
public static <T extends Enum<T>> Collector<T, ?, Map<T, Long>> counting(Class<T> type) {
return Collectors.toMap(
Function.<T>identity(),
x -> 1l,
Long::sum,
() -> new HashMap(Stream.of(type.getEnumConstants()).collect(Collectors.toMap(Function.<T>identity(),t -> 0l)))
);
}
list.stream()
.map(Person::getFavouriteColor)
.collect(counting(Color.class))
謝謝,我找到了一種方法來推廣所有枚舉類型的解決方案。 – rascio