Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting multiple fields from one list and save it to another list or same type new list. In java 8

I have a list of user List<User> "abc".

class User {
int id;
String name;
String address;
.....//getters and setters
}

I only need to extract name and address from the List<User> and save to another new list object List<User> "xyz". Or some new list which have two String fields name and address. e.g.:

class SomeClass {
String name;
String address;
........//getters and setters
}

I know that it can be done by iterating the original list and save to another new list object. But I want to know that how it can be done in Java 8 more efficiently. By using streams(), map()… etc. And with using default constructor.

like image 966
SudeepShakya Avatar asked Feb 06 '23 20:02

SudeepShakya


1 Answers

List<SomeClass> list = users.stream()
                            .map(user -> new SomeClass(user.getName(), user.getAddress()))
                            .collect(Collectors.toList());
like image 189
kjsebastian Avatar answered Feb 08 '23 14:02

kjsebastian