Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List iteration & setting values with Java 8 Streams API

I'm trying to understand how to use the Java 8 Streams API.

For example, I have these two classes:

public class User {
    private String name;
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
}

public class UserWithAge {
    private String name;
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    private int age;
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}

I have a List<User> of ten users, and I want to convert this to a List<UserWithAge> of ten users with the same names and with a constant age (say, 27). How can I do that using the Java 8 Streams API (without loops, and without modifying the above classes)?

like image 920
jd2050 Avatar asked Jan 04 '23 09:01

jd2050


2 Answers

You could use the map() feature of the stream to convert each User instance in your list to a UserWithAge instance.

List<User> userList = ... // your list

List<UserWithAge> usersWithAgeList = userList.stream()
        .map(user -> {
                // create UserWithAge instance and copy user name
                UserWithAge userWithAge = new UserWithAge();
                userWithAge.setName(user.getName());
                userWithAge.setAge(27);
                return userWithAge;
         })
         .collect(Collectors.toList()); // return the UserWithAge's as a list
like image 70
Floern Avatar answered Jan 13 '23 19:01

Floern


While you could do this, You should not do like this.

List<UserWithAge> userWithAgeList = new ArrayList<UserWithAge>();

userList.stream().forEach(user -> {
                UserWithAge userWithAge = new UserWithAge();
                userWithAge.setName(user.getName());
                userWithAge.setAge(27);
                userWithAgeList.add(userWithAge);
});
like image 45
WannaBeCoder Avatar answered Jan 13 '23 20:01

WannaBeCoder