I wanna make streams from a list, and do something with an object if an certain field is true.
Let me show you what have I done till now:
List<UserData> userDataList = new ArrayList<>();
phoneNumbers.forEach(phoneNumber -> {
if (phoneNumber.getPrimary()) {
UserData userData = new UserData();
userData.setDescription(phoneNumber.getType());
userData.setValue(phoneNumber.getNumber);
userDataList.add(userData);
}
});
So if phoneNumber.getPrimary() == true
will do the following task, if not -
ignore it.
Yes, you can combine filter
with map
to transform the List
of relevant elements into a Stream
of UserData
, and then collect them into a List
:
List<UserData> userDataList =
phoneNumbers.stream()
.filter(p -> p.getPrimary()) // or filter(ClassName::getPrimary)
.map(p -> {
UserData userData = new UserData();
userData.setDescription(p.getType());
userData.setValue(p.getNumber());
return userData;
})
.collect(Collectors.toList());
And if UserData
has a constructor that takes the type and number, you can make the code shorter:
List<UserData> userDataList =
phoneNumbers.stream()
.filter(p -> p.getPrimary()) // or filter(ClassName::getPrimary)
.map(p -> new UserData(p.getType(),p.getNumber()))
.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