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?

1
  • 1
    Why don't you do String str = String.join("", map.get("A"));? Commented Jan 18, 2023 at 11:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I added the type (also in my questiong) - did not help.
Sorry, I forgot the flatMap - its working with it!
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.