hades
hades

Reputation: 4696

Java 8 map each field value of a List to another similar List

I have 2 List of objects:

List<User>
List<UserResource>

For User class:

public class User {

    private int id;

    private String name;

    private String address; 

    **SETTERS & GETTERS**
}

For UserResource class:

public class UserResource {

    private String name;

    private String address; 

    **SETTERS & GETTERS**
}

My List<User> has data and i want to map value in name and address to UserResource's name and address, using java 8 stream and lambda, but i not sure how to do it.

Search online for quite sometime but not able to find similar question. Something like:

List<User> users = **data inserted**
List<UserResource> resources = users.forEach(u ->{
    u.setName(users.getName());
    u.setAddress(users.getAddress());
});

I tried something like following, but im not using constructor, not really sure how to fix it.

List<UserResource> userResources = users.stream().map(u -> new UserResource(u.getName(), u.getAddress())).collect(Collectors.toList());

Upvotes: 1

Views: 1671

Answers (1)

Eugene
Eugene

Reputation: 120848

Your edit is logically correct, I assume you want to do it via setters, in this case define a lambda body and perform the operations there...

.map(u -> { 
     UserResource ur = new UserResource();
     ur.setName(u.getName());
     ur.setAddress(u.getAddress());
     return ur;
 }).collect(...)

Upvotes: 5

Related Questions