I have map Map<Nominal, Integer> with objects and their counts:
Map<Nominal, Integer>
a -> 3 b -> 1 c -> 2
And I need to get such
And I need to get such ,java,collections,stream"/>
首页 > 解决方案 > 如何收集数据到 List from Map using java Stream API? I have map Map<Nominal, Integer> with objects and their counts: a -> 3 b -> 1 c -> 2 And I need to get such java - 如何收集数据到 List from Map using java Stream API? I have map Map<Nominal, Integer> with objects and their counts: a -> 3 b -> 1 c -> 2 And I need to get such 问题描述 I have map Map<Nominal, Integer> with objects and their counts: a -> 3 b -> 1 c -> 2 And I need to get such a List<Nominal> from it: a a a b c c How can I do this using the Stream API? Stream the entries and use flatMap to generate multiple copies of each key based on the value. List<Nominal> expanded = map.entrySet().stream() .flatMap(e -> generate(e::getKey).limit(e.getValue())) .collect(toList()); 标签: javacollectionsstream 解决方案 We can use Collections::nCopies to achieve the desired result: 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()); } Ideone demo Remark In the demo, I changed the key-type of the Map from Nominal to Object since the definition of Nominal was not provided. Changing the key-type, however, does not influence the solution. 推荐阅读 coupon - 如何从 WooCommerce 预订中的取消预订中创建优惠券?azure - PowerShell Azure Functions $TriggerMetadata Methode 是 GET 但应该是 POSTpython - 为什么我的不和谐机器人无法使用自定义动画表情符号?python - ModuleNotFoundError sklearn.preprocessing, Pickleandroid - Jetpack 编写代码以在单击文本时向下滚动到特定 UI 元素的位置javascript - NODE.JS 如何在不填满存储空间的情况下保存 JSON 数据java - AABB 检测边缘碰撞 [libGDX]node.js - 如何从 REACT FORM 获取 POST 数据到 MongoDBpython - 从 WSDL 文件生成 webservice 服务器django - DRF Viewset 测试方法
And I need to get such a List<Nominal> from it:
List<Nominal>
a a a b c c
How can I do this using the Stream API?
Stream the entries and use flatMap to generate multiple copies of each key based on the value.
List<Nominal> expanded = map.entrySet().stream() .flatMap(e -> generate(e::getKey).limit(e.getValue())) .collect(toList());
标签: javacollectionsstream
We can use Collections::nCopies to achieve the desired result:
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()); }
Ideone demo
In the demo, I changed the key-type of the Map from Nominal to Object since the definition of Nominal was not provided. Changing the key-type, however, does not influence the solution.
Map
Nominal
Object