且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为具有不同属性的多个类调用过滤器和排序方法?

更新时间:2023-10-29 17:34:58

您可以使buildGroup接受Collection<? extends T>Function<? super T, Integer>,以便它可以使用函数将集合元素映射为整数:

You can make buildGroup accept Collection<? extends T> and Function<? super T, Integer> so that it can use a function to map collection elements to integers:

public <T> List<T> buildGroup(
        Collection<? extends T> entities,
        Function<? super T, Integer> property,
        int from, int to, int sum
) {
    return entities.stream()
            .filter(elm -> isPropertyMatch(property.apply(elm), from, to, sum))
            .sorted(Comparator.comparing(property))
            .collect(Collectors.toList());
}

isPropertyMatch所在的位置:

private static boolean isPropertyMatch(Integer value, int from, int to, int sum) {
    if(value == null) return false;
    return value >= from && value <= to || value.equals(sum);
}

用例:

buildGroup(kEntityList, KEntity::getDb_1, from, to, sum);