Search code examples
javafilterjava-stream

How to use multiple filters + map in the same stream?


How do I merge this to a single stream? The goal is to get all the row numbers in a single list.

List<Integer> Type1ErrorRows = errors.stream()
        .filter(c -> (c.getClass() == Type1Error.class))
        .map(c -> ((Type1Error) c).getRowNumber())
        .collect(Collectors.toList());

List<Integer> Type2ErrorRows = errors.stream()
        .filter(c -> (c.getClass() == Type2Error.class))
        .map(c -> ((Type2Error) c).getRowNumber())
        .collect(Collectors.toList());

List<Integer> rowNumbers =
        Stream.concat(Type1ErrorRows.stream(), Type2ErrorRows.stream())
                .collect(Collectors.toList());

Solution

  • I'll assume that a common interface exists, otherwise all the required casting will make it too cumbersome for streams.

    public interface ErrorInterface {
    
      int getRowNumber();
    }
    

    Filter that object's class is allowed, cast, invoke method to get row number.

    Set<Class<?>> allowedClasses = Set.of(Type1Error.class, Type2Error.class);
    List<Integer> rowNumbers = errors.stream()
            .filter(err -> allowedClasses.contains(err.getClass()))
            .map(err -> (ErrorInterface) err)
            .map(ErrorInterface::getRowNumber)
            .toList();