I am having a List
of class Person
. The Person
class looks like this:
JavaScript
x
public class Person {
int id;
String username;
double balance;
String gender;
boolean isPersonWorking;
// All-args constructor, getters and setters omitted for brevity
}
Below is how I am declaring and initializing my List<Person>
:
JavaScript
List<Person> personsList = new ArrayList<>();
personsList.add(new Person(1, "James", 300, "Male", true));
personsList.add(new Person(2, "Jane", 500, "Female", false));
personsList.add(new Person(3, "Valjakudze", 900, "Male", false));
personsList.add(new Person(4, "Laika", 1200, "Female", true));
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
List<String> personsNamesUsingStream = new ArrayList<>();
personsNamesUsingStream = personsList.stream()
.map(person -> person.getUsername());
But I am getting below error
JavaScriptRequired type: List<String> Provided: Stream<Object>
no instance(s) of type variable(s) R exist so that Stream<R> conforms to List<String>`
Advertisement
Answer
Your problem is here :
JavaScript
personsNamesUsingStream = personsList.stream().map(person -> person.getUsername());
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
personsNamesUsingStream = personsList.stream().map(Person::getUsername).collect(Collectors.toList());