Bick
Bick

Reputation: 18551

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

Upvotes: 7

Views: 2562

Answers (2)

Eran
Eran

Reputation: 394156

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

Upvotes: 9

Eugene
Eugene

Reputation: 121088

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

Upvotes: 4

Related Questions