Home > front end >  Java Stream: Concat a string out of a map with lists
Java Stream: Concat a string out of a map with lists

Time:01-18

I try to build a string out of all elements of a list that is an element of a map.

Map <String, List <String>> map = new HashMap <String, List <String>> ();
map.put ("A", new ArrayList <String> () {{ add ("a"); add ("b"); add ("c"); }});
map.put ("N", new ArrayList <String> () {{ add ("1"); add ("2"); add ("3"); }});
    

String str = map.entrySet ().stream ()
        .filter (x -> x.getKey ().equals ("A"))         // list of map-entry "A"
        .map (x -> x.getValue ().stream ())             // every list-element
        .collect (Collectors.joining ());               // join to str

I try to get "abc" inside of str.

Instead I get an error of the compiler ;-)

Compiler-error:

The method collect(Collector<? super Stream,A,R>) in the type Stream<Stream> is not applicable for the arguments (Collector<CharSequence,capture#1-of ?,String>)    

I am not very good with stream-expressions. Where is the problem?

CodePudding user response:

There are 2 problems with your code:

  1. You need to use Stream.flatMap(), not Stream.map(), for the mapping operation.

Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

  1. The map declaration is missing the type of the list
Map<String, List> map = ...

should be:

Map <String, List<String>> map = ...;

Without it the compiler won't be able to infer the type of the elements and Collectors.joining() can only be used on CharSequence - strings, etc.

  • Related