Java 8 Lambdas and Streams... not a "how" , but a "why"? -
this question has answer here:
the question have involves both lambdas , streams. there couple of things can't resolve. starting lambdas, using predicate example.
notice how in following code neither import "java.util.function.predicate
" nor implement predicate interface in class declaration. , yet, lambda works fine. why that?
public class using_predicate { public static list<integer> numbers = arrays.aslist(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); public static void main(string[] args) { // passing numbers list , different lambdas intermediate // function. system.out.println(); printvals(numbers, x -> x > 6); // values greater 6 system.out.println(); printvals(numbers, x -> x % 2 == 0); // values system.out.println(); printvals(numbers, x -> x < 8); // ll values less 8 system.out.println(); printvals(numbers, x -> x % 2 == 1); // odd values } //intermediate predicate function public static void printvals(list<integer> val, predicate<integer> condition) { (integer v : val) { if (condition.test(v)) // if true, print v system.out.print(v + " "); } } }
notice how have employ "intermediate function" utilizes "test()" method of predicate functional interface. however, if decide similar in using stream, again neither have import java.util.function.predicate, or java.util.stream, or implement predicate interface in class declaration. furthermore, can use predicate lambda in stream without having create intermediate function! why that?
for example:
// predicate lambda prints first value greater 3, in case 5 public class sample1 { public static void main(string[] args) { list<integer> values = arrays.aslist(1, 2, 3, 5, 4, 6, 7, 8, 9, 10); system.out.println( values.stream() .filter(e -> e > 3) .findfirst() ); } }
so, confused on "why" of rules lambdas , streams, not on "how".
imports used allow not have write complete package name of class. in case need import predicate
if use word predicate
somewhere in code. if example did have use word predicate
, instead wrote out full package name, java.util.function.predicate
, not need include import.
import not used providing code public api of class. not need import predicate
create lambda predicate
. compiler knows predicate
class being referred filter
method.
Comments
Post a Comment