Nev*_*eps 2 java collections stream
我有Map<Nominal, Integer>对象及其计数的地图:
a -> 3
b -> 1
c -> 2
Run Code Online (Sandbox Code Playgroud)
我需要从中得到这样的List<Nominal>:
a
a
a
b
c
c
Run Code Online (Sandbox Code Playgroud)
如何使用 Stream API 执行此操作?
我们可以使用Collections::nCopies来达到预期的效果:
private static <T> List<T> transform(Map<? extends T, Integer> map) {
return map.entrySet().stream()
.map(entry -> Collections.nCopies(entry.getValue(), entry.getKey()))
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
在演示中,我改变了按键式的Map,从Nominal到Object自定义Nominal未提供。但是,更改密钥类型不会影响解决方案。