简体   繁体   中英

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

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>>

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 (ie 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()));

If you want your List<String> to be composed of propertyValue , than:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM