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:

JavaScript

I need to obtain the output:

JavaScript

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

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().
JavaScript

Use this link to play around with Online demo

Advertisement