Search code examples
java-8java-stream

Java 8 replacing operation in a stream


I have a list of Users . Now i want to replace a User satisfying the condition if user.getAge() is equal to 25 then a method will change that user object properties and add it to the existing list replacing the old User. How we can do this in Java 8. I have come this much

List<User> usersWithModifiedUsers = users.stream().filter(e-> e.getAge()>25).map(e-> modify(e))

But confused with the rest, can anyone help ?


Solution

  • Try this.

    If you just want the list of modified users, then filter and map.

    List<User> usersModified = users
        .stream()
        .filter(e-e.getAge() > 25)
        .map(e->modify(e))
        .collect(Collectors.toList());
    

    If you want all the users with the altered and unaltered, then do a map.

    users = users
        .stream()
        .map(e-> e.getAge() > 25 ? modify(e) : e )
        .collect(Collectors.toList());
    

    Note that in the first case, you should be able to pass a method reference for modify