Search code examples
javajava-streamreducepredicate

How to create 2 lists from one list based on predicate using stram().reduce()


I need to create 2 lists based on a predicate by using stream().reduce(). I got a similar code but it's not working.

localRequestDTOList.stream().reduce((res, item) ->{
       res[predicate(item) ? 'a' : 'b'].push(item);
       return res;
}, { a: [], b: [] });

The predicate is shown below.

public static Predicate<LocalRequestDTO> payToVendor() {
    return request -> (request.getSuffix().equals("00"));
}

What I want is from localRequestDTOList create two lists with the condition that their request.getsuffix().equals("00") or not. I simply put the two lists as a and b.


Solution

  • You asked about how to partition a list by using reduce. That's like asking how to hammer a nail using a screwdriver. It would be better to use the correct method for the purpose.

    If you can use collect() then you could make use of Collectors.partitioningBy():

    Map<Boolean, List<LocalRequestDTO>> partition = localRequestDTOList.stream()
        .collect(Collectors.partitioningBy(payToVendor()));
    List<LocalRequestDTO> a = partition.get(true);
    List<LocalRequestDTO> b = partition.get(false);