Reputation: 621
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.
Upvotes: 4
Views: 3825
Reputation: 1279
List<SomeClass> list = users.stream()
.map(user -> new SomeClass(user.getName(), user.getAddress()))
.collect(Collectors.toList());
Upvotes: 8