Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 streams do something with an element which has a boolean field

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.

like image 305
Florin Lei Avatar asked Jul 05 '17 11:07

Florin Lei


1 Answers

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());
like image 105
Eran Avatar answered Nov 10 '22 13:11

Eran