简体   繁体   中英

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. eg:

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.

List<SomeClass> list = users.stream()
                            .map(user -> new SomeClass(user.getName(), user.getAddress()))
                            .collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM