4

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)?

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

Comments

2

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);
});

2 Comments

Does userWithAgeList have to be final?
@GrzegorzGórkiewicz variables used within stream operations should be final or effectively final otherwise issues may arise. (consider parallel use of the stream by separate threads)
0
public class ListIteratorExp {

    public static void main(String[] args) {
        List<Person> list = new ArrayList<>();
        Person p1 = new Person();
        p1.setName("foo");

        Person p2 = new Person();
        p2.setName("bee");

        list.add(p1);
        list.add(p2);

        list.stream().forEach(p -> {
            String name = p.getName();
            System.out.println(name);
        });
    }

}
class Person{
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}
output:-
vishal
thakur

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.