Skip to content
Advertisement

Lists stream().map() no instance(s) of type variable(s) R exist so that Stream conforms to List

I am having a List of class Person. The Person class looks like this:

JavaScript

Below is how I am declaring and initializing my List<Person>:

JavaScript

What i want to achieve is to get a List<String> of all usernames using the Java Stream API, but not using for loop.

Below is how I have tried to implement this:

JavaScript

But I am getting below error

JavaScript

Advertisement

Answer

Your problem is here :

JavaScript

The result of .map() is a stream of Objects , exactly it is a Stream of Strings, and your reference personsNamesUsingStream is from type List<String> so you cannot assigne the result of .map() to a reference from List.

The solution is to store the elements of your stream of String into an ArrayList<String> and like that you can use your reference personsNamesUsingStream .

The code correction :

JavaScript
Advertisement