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.
List<SomeClass> list = users.stream()
.map(user -> new SomeClass(user.getName(), user.getAddress()))
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With