Grouping Java8 threads in enumeration and counting

With classes:

public class Person {

    private String name;
    private Color favouriteColor;
}

public enum Color {GREEN, YELLOW, BLUE, RED, ORANGE, PURPLE}

Having List<Person>using the Java8 Stream API, I can convert it to Map<Color, Long>having a counter for each Color, also for colors that are not on the list. Example:

List<Person> list = List.of(
    new Person("Karl", Color.RED),
    new Person("Greg", Color.BLUE),
    new Person("Andrew", Color.GREEN)
);

Convert this list to a map with all listing colors with their counter.

thank

solvable

It was decided to use a custom collector:

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))
+4
source share
2 answers

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));

, , :

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;
    }));

, , :

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)))));

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));
+8

:

Map<Color, Long> counted = list.stream()
        .collect(Collectors.groupingBy(Person::getFavouriteColor(), 
                                       Collectors.counting()));

, , getter Person#favouriteColor.

, Color , Color, , , 0:

Stream.of(Color.values())
      .filter(x -> !counted.containsKey(x))
      .forEach(x -> counted.put(x, 0L));
+3

Source: https://habr.com/ru/post/1598871/


All Articles