Home > front end >  Getting an error while trying to map a list of objects
Getting an error while trying to map a list of objects

Time:02-08

i'm trying to map this list :

mappedCustomers = customers.stream().map(e ->e.setLastName("e")).collect(Collectors.toList());

Customer Class

@Entity

@Table(name = "customer") public class Customer {

@Id
@GeneratedValue
Long id;

String firstName;

String lastName;

public Long getId() {
    return id;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

}

but I'm getting this error:

no instance(s) of type variable(s) R exist so that void conforms to R enter image description here

CodePudding user response:

Map function from the Stream API, is expecting a function that return a value.

<R> Stream<R> map(Function<? super T,? extends R> mapper)

However setters return value is void (no return value at all), therefore your code does not comply with the map method signature, if you want to iterate over a collection and execute an operation you could use forEach

void forEach(Consumer<? super T> action)

No need to do the collection as you initial collection will be the same but it will contain your modification.

customers.stream().forEach(x -> x.setLastName("e"))

CodePudding user response:

map() returns a new stream, so you can chain another operation if you need. Then, collect() returns a new list. But since you only call a setter, you end up with two lists containing the same objects. In this case, forEach() would be simpler.

customers.stream().forEach(e -> e.setLastName("e"));
  •  Tags:  
  • Related