Search code examples
javalambdafilterjava-streamcollectors

How to, from a list, filter it and convert to Map<String,String>


I am trying to, from a list of Strings, filter it, and load the results into a Map<String,String> of with the strings that passed through the test and a generic reason.

This is why I am trying:

Map<String,String> invalidStrings = null;

invalidStrings = src.getAllSubjects()
                 .stream()
                 .filter(name -> !(name.contains("-value") || name.contains("-key")))
                 .collect(Collectors.toMap(Function.identity(), "Some Reason"));

This is what I am getting:

The method toMap(Function, Function) in the type Collectors is not applicable for the arguments (Function, String)

No idea why I am not being able to do this... Everywhere I search the suggestions are basically the same as I am doing.


Solution

  • This is the important part of the error:

    The method toMap(Function, Function) <--- note the Function, Function

    This means, toMap expects the first argument to be a function which you've done correctly via Function.identity() i.e. v -> v but the second value you've passed is a String

    Rather the value mapper must be a function:

     .collect(Collectors.toMap(Function.identity(), v -> "Some Reason"));
    

    note the v -> "Some Reason";