How to reuse application of filter & map on a Stream?

前端 未结 3 1082
既然无缘
既然无缘 2021-02-13 12:34

I have a set of domain objects that inherit from a shared type (i.e. GroupRecord extends Record, RequestRecord extends Record). The subtypes have speci

3条回答
  •  无人共我
    2021-02-13 13:15

    You don’t need an entire class to encapsulate a piece of code. The smallest code unit for that purpose, would be a method:

    public static  Stream filter(Collection source, Class type) {
        return source.stream().filter(type::isInstance).map(type::cast);
    }
    

    This method can be used as

    SomeStatsResult stats1 = filter(records, GroupRecord.class)
                                .collect(...);
    SomeStatsResult stats2 = filter(records, GroupRecord.class)
                                .collect(...);
    

    If the filtering operation isn’t always the first step in your chain, you may overload the method:

    public static  Stream filter(Collection source, Class type) {
        return filter(source.stream(), type);
    }
    public static  Stream filter(Stream stream, Class type) {
        return stream.filter(type::isInstance).map(type::cast);
    }
    

    However, if you have to repeat this operation multiple times for the same type, it might be beneficial to do

    List groupRecords = filter(records, GroupRecord.class)
                                .collect(Collectors.toList());
    SomeStatsResult stats1 = groupRecords.stream().collect(...);
    SomeStatsResult stats2 = groupRecords.stream().collect(...);
    

    not only eliminating the code duplication in source code, but also performing the runtime type checks only once. The impact of the required additional heap space depends on the actual use case.

提交回复
热议问题