What is the difference between a Predicate and a Function Interface in Java8?

  • A+
Category:Languages

I know it may be a very basic question on SO but I am new to Java8.I want to know what is the difference between a Predicate and a Function Interface in Java8?

Predicate<String> predicateTest  = (s)-> s.length() > 5;        System.out.println(predicateTest.test("Predicate"));  Function<String, Boolean> functionTest = str -> str.length()> 5;       System.out.println(functionTest.apply("Function")); 

Here in my Example both are returning true.The only thing is way of calling is different ?

 


Predicate<String> and Function<String, Boolean> are the same thing in terms of what they represent i.e. they both represent a function taking a String and returning a boolean. However, the former avoids boxing the returned value from boolean to Boolean whereas the latter does not.

That said, this does not necessarily mean wherever you can use a Predicate<String> you can also use a Function<String, Boolean> or vice versa.

Example:

While this compiles:

Predicate<String> predicate = p -> p.length() == 21; Stream<String> stream = stringList().stream().filter(predicate); 

This does not:

Function<String, Boolean> function = p -> p.length() == 21; Stream<Boolean> stream = stringList().stream().filter(function); 

and vice versa:

While this works:

Function<String, Boolean> function = p -> p.length() == 21; Stream<Boolean> stream = stringList().stream().map(function); 

This does not:

Predicate<String> predicate = p -> p.length() == 21; Stream<String> stream = stringList().stream().map(predicate); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: