Without using Lambda Expression, the highlighted code would need to be like this,
We can use this SortedCounter to count the course selected by the classmates of a given student to recommend courses to the student, there are many occurrences of lambda expression in the above example,
in the above class, the parameter for SortedCounter and one forEach loop are the examples for Lambda Expression.
//Declare a Predicate using lambda expression Predicate<String> notContains = course -> !courses.contains(course); //Passing a lambda expression as a constructor parameter SortedCounter<String> sortedCounter = new SortedCounter<>( (course1, course2) -> course1.compareTo(course2)); //Both forEach calls take a lambda expression as parameter classmateService.getClassmates(student) .forEach( classmate -> courseService.getCources(classmate) .stream() .filter(notContains).forEach( purchase -> sortedCounter.count(purchase) ) );
We can use interface to switch the cache evict policy, and use SortedCounter class in Least Frequently Used cache policy,
Least Frequently Used eviction policy,
and a self populating cache,
Award::new is called method reference in Java 8, the alternative is a lambda expression or Anonymous Inner Class,the following 3 code snippets have the same functionality.
//Use method reference private final static SelfPopulatingCache<Integer, Award> AWARDS = create(Award::new);
//Using lambda expression private final static SelfPopulatingCache<Integer, Award> AWARDS = create(level -> new Award(level));
//Before Java 8, using Anonymous Inner Class private final static SelfPopulatingCache<Integer, Award> AWARDS = create( new SelfPopulatingCache.Creator<Integer, Award>() { @Override public Award create(Integer key) { return new Award(level); } }); }This test make sure the valueOf return the same instance even under load, the highlighted code is also an example of lambda expression,
and this is the code without it,
No comments:
Post a Comment