gpt4 book ai didi

Java8流分组通过枚举和计数

转载 作者:搜寻专家 更新时间:2023-10-31 08:22:32 24 4
gpt4 key购买 nike

与类:

public class Person {

private String name;
private Color favouriteColor;
}

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

有一个 List<Person>我可以使用 Java8 Stream API 将其转换为 Map<Color, Long>计算每个 Color ,也适用于列表中未包含的颜色。示例:

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

使用枚举的所有颜色及其计数在 map 中转换此列表。

谢谢

已解决

使用自定义收集器解决:

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

最佳答案

您可以使用 groupingBy 收集器来创建映射,但是如果您想为不存在的键添加默认值,则必须通过提供 Supplier< 来确保返回的映射是可变的 用于 map 。另一方面,这增加了创建更适合此用例的 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));

可能是,您认为在 supplier 函数中使用默认值填充映射更清晰:

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

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

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

关于Java8流分组通过枚举和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31537763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com