Skip to content
Advertisement

How to iterate over a Map to obtain a String of repeated Character Keys with Java 8

I have a Map shown below:

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:

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.
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 method String.join();
  • combine the strings together using collector joining().
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

Advertisement