Generic method to perform a map-reduce operation. (Java-8)

前端 未结 3 2095
时光说笑
时光说笑 2021-01-02 12:02

How to overload a Function with generic parameter in Java 8?

public class Test {

    List list = new ArrayList<>();

    public int          


        
3条回答
  •  长发绾君心
    2021-01-02 12:31

    Benji Weber once wrote of a way to circumvent this. What you need to do is to define custom functional interfaces that extend the types for your parameters:

    public class Test {
    
        List list = new ArrayList<>();
    
        @FunctionalInterface
        public interface ToIntFunction extends Function{}
        public int sum(ToIntegerFunction function) {
            return list.stream().map(function).reduce(Integer::sum).get();
        }
    
    
        @FunctionalInterface
        public interface ToDoubleFunction extends Function{}
        public double sum(ToDoubleFunction function) {
            return list.stream().map(function).reduce(Double::sum).get();
        }
    }
    

    Another way is to use java.util.function.ToIntFunction and java.util.function.ToDoubleFunction instead:

    public class Test {
    
        List list = new ArrayList<>();
    
        @FunctionalInterface
        public int sum(ToIntFunction function) {
            return list.stream().mapToInt(function).sum();
        }
    
        public double sum(ToDoubleFunction function) {
            return list.stream().mapToDouble(function).sum();
        }
    }
    

提交回复
热议问题