-2

I am studying this Functional Interface subject, and I studies how to use the pre-defined functional interfaces: Predicate and Function.

So I created several implementations:

public static Predicate<String> isStringEmpty = String::isEmpty;
public static Predicate<String> isStringNotEmpty = isStringEmpty.negate();
public static Predicate<ArrayList> arrayListIsEmpty = ArrayList::isEmpty;
public static Predicate<ArrayList> arrayListIsNotEmpty = arrayListIsEmpty.negate();
public static Predicate<String> stringStartsWithA = s -> s.startsWith("A");
public static Predicate<Integer> largerThanNine = n -> n > 9;

public static Function<WebElement, String> getWebElementText = WebElement::getText;
//etc.

And I went on to use them in my code. For example:

isStringEmpty.negate().test("asd");
isStringNotEmpty.test("asd");
stringStartsWithA.negate().test("asd");
isStringNotEmpty.and(isStringEmpty).negate().test("aaa");

csvLine = getWebElementText.apply(leaugeRowElement);

I cannot understand what is our gain in using this form of testing a condition or calling a function? (I am sure there is such!)

How is this different than simply calling a regular function to do these tasks?

Is it for allowing lambdas to use them? Is it to allow passing them as methods arguments?

I surly miss out the real reasoning for this technique.

Can you explain me please?

Thanks!

dushkin
  • 1,939
  • 3
  • 37
  • 82
  • "For example:" You can only really claim an advantage of something when compared to another. What alternative do you have in mind for these? – Andy Turner Feb 05 '21 at 14:21
  • 1
    *How is this different than simply calling a regular function to do these tasks?* What if you wanted to pass the method to another method and have that method invoke it? – WJS Feb 05 '21 at 14:23
  • 1
    Another case of textbooks failing to explain functional interfaces and lambdas from the right angle. – ernest_k Feb 05 '21 at 14:27
  • 1
    Does this answer your question? [What are functional interfaces used for in Java 8?](https://stackoverflow.com/questions/36881826/what-are-functional-interfaces-used-for-in-java-8) – SRJ Feb 05 '21 at 14:40

1 Answers1

1

Your questions could be answered if you read manual about functional interfaces and lambdas. Just take a look on difference between lambda expression and usual anonymous class creation. Both variables can be used the same way.

    //using anonymous class 
    Predicate<String> isStringEmptyObj = new Predicate<String>() {
        @Override
        public boolean test(String o) {
            return o.isEmpty();
        }
    };
    System.out.println(isStringEmptyObj.negate().test("asd"));

    //using lambda with reference to existing String object method
    Predicate<String> isStringEmpty = String::isEmpty;
    System.out.println(isStringEmpty.negate().test("asd"));
Sergey Afinogenov
  • 2,137
  • 4
  • 13