1

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?

chris01
  • 10,921
  • 9
  • 54
  • 93

1 Answers1

3

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.

Chaosfire
  • 4,818
  • 4
  • 8
  • 23
  • I added the type (also in my questiong) - did not help. – chris01 Jan 18 '23 at 10:48
  • Sorry, I forgot the flatMap - its working with it! – chris01 Jan 18 '23 at 10:50
  • 1
    @chris01 there’s still no sense in streaming over an entire map, to perform a linear search for a key, when every `Map` has an efficient `get` method precisely for the purpose of getting the value for a key. So, `String str = String.join("", map.get("A"));` does the entire job. And [don’t use the double brace initialization anti-pattern](https://stackoverflow.com/a/27521612/2711488) – Holger Jan 19 '23 at 12:59