Reputation: 1326
Here's desired behavior:
[A: 4, B: 2, C: 3, D: 3] -> [A,A,A,A,B,B,C,C,C,D,D,D]
I wrote some code to tackle this.. Here's the code:
Map<String, Integer> terms = new HashMap<>();
Stream.of(terms.entrySet())
.flatMap(entry -> {
List<String> items = new ArrayList<>();
for (int i = 0; i < entry.getValue(); i++) {
items.add(entry.getKey());
}
return Stream.of(items);
})
.forEach(System.out::println);
Is there a better way to do this? I'm relatively new to Rx, so I want to know if there's a best practice or something like that.
Upvotes: 0
Views: 227
Reputation: 7880
How about this:
terms.keySet().stream()
.map(s -> IntStream.range(0, map.get(s))
.mapToObj(i -> s).collect(Collectors.toList()))
.flatMap(List::stream)
.collect(Collectors.toList());
Upvotes: 2