Java8流分组通过枚举和计数

ras*_*cio 5 java java-8 java-stream collectors

随着课程:

public class Person {

    private String name;
    private Color favouriteColor;
}

public enum Color {GREEN, YELLOW, BLUE, RED, ORANGE, PURPLE}
Run Code Online (Sandbox Code Playgroud)

有一个List<Person>我使用Java8流API可以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)
);
Run Code Online (Sandbox Code Playgroud)

在地图中使用枚举的所有颜色及其计数来转换此列表.

谢谢

解决了

使用自定义收集器解决:

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))
Run Code Online (Sandbox Code Playgroud)

Hol*_*ger 10

您可以使用groupingBy收集器创建映射,但如果要为缺少的键添加默认值,则必须通过为Supplier映射提供一个来确保返回的映射是可变的.另一方面,这增加了创建EnumMap更适合此用例的机会:

EnumMap<Color, Long> map = list.stream().collect(Collectors.groupingBy(
    Person::getFavouriteColor, ()->new EnumMap<>(Color.class), Collectors.counting()));
EnumSet.allOf(Color.class).forEach(c->map.putIfAbsent(c, 0L));
Run Code Online (Sandbox Code Playgroud)

可能是,您认为使用供应商函数中的默认值填充地图会更清晰:

EnumMap<Color, Long> map = list.stream().collect(Collectors.toMap(
    Person::getFavouriteColor, x->1L, Long::sum, ()->{
        EnumMap<Color, Long> em = new EnumMap<>(Color.class);
        EnumSet.allOf(Color.class).forEach(c->em.put(c, 0L));
        return em;
    }));
Run Code Online (Sandbox Code Playgroud)

但当然,您也可以使用流来创建初始地图:

EnumMap<Color, Long> map = list.stream().collect(Collectors.toMap(
    Person::getFavouriteColor, x->1L, Long::sum, () ->
        EnumSet.allOf(Color.class).stream().collect(Collectors.toMap(
        x->x, x->0L, Long::sum, ()->new EnumMap<>(Color.class)))));
Run Code Online (Sandbox Code Playgroud)

但是为了完整性,如果您愿意,可以在没有流API的情况下执行相同的操作:

EnumMap<Color, Long> map = new EnumMap<>(Color.class);
list.forEach(p->map.merge(p.getFavouriteColor(), 1L, Long::sum));
EnumSet.allOf(Color.class).forEach(c->map.putIfAbsent(c, 0L));
Run Code Online (Sandbox Code Playgroud)