Home > Mobile >  Lists stream().map() no instance(s) of type variable(s) R exist so that Stream<R> conforms to
Lists stream().map() no instance(s) of type variable(s) R exist so that Stream<R> conforms to

Time:03-16

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

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>:

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:

List<String> personsNamesUsingStream = new ArrayList<>();
personsNamesUsingStream = personsList.stream()
    .map(person -> person.getUsername());

But I am getting below error

Required type: List<String> Provided: Stream<Object>
no instance(s) of type variable(s) R exist so that Stream<R> conforms to List<String>`

CodePudding user response:

tl;dr

You neglected to produce a list from your stream.

List.of(
    new Person( 1 , "Alice" ) ,
    new Person( 2 , "Bob" ) ,
    new Person( 3 , "Carol" ) 
)
.stream()
.map( Person :: name )
.toList()  //            
  • Related