Java 8 streams - How do I manipulate value in a group by result?

Bick :

I have a list of objects with two String fields like

Name1, Active
Name2, InActive
Name3, InActive
Name4, Active

And I would like to have a

Map<Boolean, List<String>>

where Active=true and InActive=false.

I tried

active = dualFields.stream().collect(
       Collectors.groupingBy( 
           x -> StringUtils.equals(x.getPropertyValue(), "Active")));

But I received

Map<Boolean, List<DualField>>
Eran :

First of all, you can use partitioningBy, which is a special case of groupingBy (where you are grouping by a Predicate into two groups). You can map the objects to the required Strings with mapping.

I'm assuming you want the List<String> to contain the values of the second property (i.e. not getPropertyValue(), which contains "Active" or "InActive"):

Map<Boolean,List<String>> map =
    dualFields.stream()
              .collect(Collectors.partitioningBy(x -> StringUtils.equals(x.getPropertyValue(), "Active"),
                                                 Collectors.mapping(DualField::getSecondPropertyValue,
                                                                    Collectors.toList()));

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=465810&siteId=1