Finding Max with Lambda Expression in Java -
this code
list<integer> ints = stream.of(1,2,4,3,5).collect(collectors.tolist()); integer maxint = ints.stream() .max(comparator.comparing(i -> i)) .get(); system.out.println("maximum number in set " + maxint); output:
maximum number in set 5 i cannot create distingues between 2 in bellow section of code
comparator.comparing(i -> i) can kind , explain difference between 2 i?
the method comparator.comparing(…) intended create comparator uses order based on property of objects compare. when using lambda look i -> i, short writing (int i) -> { homecoming i; } here, property provider function, resulting comparator compare values itself. works when objects compare have natural order integer has.
so
stream.of(1,2,4,3,5).max(comparator.comparing(i -> i)) .ifpresent(maxint->system.out.println("maximum number in set " + maxint)); does same as
stream.of(1,2,4,3,5).max(comparator.naturalorder()) .ifpresent(maxint->system.out.println("maximum number in set " + maxint)); though latter more efficient implemented singleton types have natural order (and implement comparable).
the reason why max requires comparator @ all, because using generic class stream might contain arbitrary objects.
this allows, e.g. utilize streamofpoints.max(comparator.comparing(p->p.x)) find point largest x value while point not have natural order. or streamofpersons.sorted(comparator.comparing(person::getage)).
when using specialized intstream can utilize natural order straight more efficient:
intstream.of(1,2,4,3,5).max() .ifpresent(maxint->system.out.println("maximum number in set " + maxint)); to illustrate difference between “natural order” , property based order:
stream.of("a","bb","aaa","z","b").max(comparator.naturalorder()) .ifpresent(max->system.out.println("maximum string in set " + max)); this print
maximum string in set z
as natural order of strings lexicographical order z greater b greater a
on other hand
stream.of("a","bb","aaa","z","b").max(comparator.comparing(s->s.length())) .ifpresent(max->system.out.println("maximum string in set " + max)); will print
maximum string in set aaa
as aaa has maximum length of strings in stream. intended utilize case comparator.comparing can made more readable when using method references, i.e. comparator.comparing(string::length) speaks itself…
java lambda max java-8
No comments:
Post a Comment