I have a Map
shown below:
JavaScript
x
Map<Character, Integer> map = new LinkedHashMap<Character, Integer>();
map.put('c', 5);
map.put('f', 2);
map.put('r', 1);
map.put('D', 3);
I need to obtain the output:
JavaScript
cccccffrDDD
I can do it in normal process, but I want to do it in Java 8. Can you share some hints how to achieve this?
Advertisement
Answer
Here’s a couple of ideas on how to approach this problem using Java 8 streams.
The overall idea:
- create a stream of map entries;
- generate a stream of single-letter strings based on each entry and merge them using built-in collector
joining()
; - apply collect with collector
joining()
to obtain the final result.
JavaScript
String joinedLetters = map.entrySet().stream()
.map(entry -> Stream.generate(() -> String.valueOf(entry.getKey()))
.limit(entry.getValue())
.collect(Collectors.joining()))
.collect(Collectors.joining());
Another way of achieving this:
- create a stream of entries;
- create a lightweight list of Strings using
Collections.nCopies()
; - turn each list into a
String
using static methodString.join()
; - combine the strings together using collector
joining()
.
JavaScript
String joinedLetters = map.entrySet().stream()
.map(entry -> Collections.nCopies(entry.getValue(), String.valueOf(entry.getKey())))
.map(list -> String.join("", list))
.collect(Collectors.joining());
Use this link to play around with Online demo