Search code examples
javalambdastring-concatenation

Java lambda expression: How to concatenate key and set of values from a hashmap?


I am new to lambda expressions and currently I am stuck with a task I'd like to solve (just for the sake of learning lambdas).

Given is a map Map<String, Set<Integer>> and I want to iterate over the entry sets concatenating the keys and their values as String.

The map could look like this:

"x", [1,3,5]

"y", [2,3]

"z", [2,4]

And I want to end up with this String representation:

"x: 1, 3, 5; y: 2, 3; z: 2, 4"

I am not even sure where to start here. All the examples that can be found on the internet do either just loop a list or a map with single values (instead of a set) and most of the time all they do is System.out.println(). I can't even figure out how to start... forEach or stream? I guess I need one (or more?) collector(s) that can join the values but I just do not understand how to achieve this. Is this even possible in one expression?

Can somebody give me a hint?


Solution

  • Like this

    Map<String, Set<Integer>> map = new HashMap<>();
    // fill map here
    String result = map.entrySet().stream()
            .map(x -> x.getKey() + ": " + x.getValue().stream()
                    .map(Object::toString)
                    .collect(Collectors.joining(", ")))
            .collect(Collectors.joining("; "));