Why doesn't Java 8's Predicate extend Function

前端 未结 4 959
慢半拍i
慢半拍i 2021-02-03 19:14

If I wrote the Predicate interface, I\'d want to encode in the interface the fact that it\'s just a function that returns a primitive boolean, like thi

4条回答
  •  佛祖请我去吃肉
    2021-02-03 19:42

    It is not a direct answer to your question, but for what would you be using it for?

    Consider the following scenario: You want to map true/false to the list of values for which it is true respectively false.

    With your code you could use:

    @FunctionalInterface
    interface CustomPredicate extends Function {
        boolean test(T value);
    
        @Override
        default Boolean apply(T t) {
            return test(t);
        }
    }
    

    List stringList = new ArrayList<>();
    stringList.add("a");
    stringList.add("hg");
    stringList.add("dsl");
    stringList.add("sldi");
    stringList.add("ilsdo");
    stringList.add("jlieio");
    CustomPredicate customPredicate = str -> (str.length() >= 3);
    Map> mapping = stringList.stream()
            .collect(Collectors.groupingBy(customPredicate));
    

    The following however tells me that they have definately thought about something similar, as they offer the partitioning method:

    List stringList = new ArrayList<>();
    stringList.add("a");
    stringList.add("hg");
    stringList.add("dsl");
    stringList.add("sldi");
    stringList.add("ilsdo");
    stringList.add("jlieio");
    Predicate predicate = str -> (str.length() >= 3);
    Map> mapping = stringList.stream()
            .collect(Collectors.partitioningBy(predicate));
    

    Some reasons I can think about are:

    • It would not be intuitive to have a apply() method available in a Predicate where you only expect a test() method.
    • Functional interfaces are designed to provide only one type of basic functionality (excluding chaining or logical operations), in your situation CustomPredicate contains two types of functionality. It would only add to confusion.

提交回复
热议问题