If you haven't realised already, the implementation of comparing basically boils down to: return (a, b) -> keyExtractor.apply(a).compareTo(keyExtractor.apply(b)) Ĭomparator#compare(T o1, T o2) Compare two objects and returns an integer value based on this criteria:Ĭparing(Function key) returns a Comparator that compares by that sort key. If you are confused by the ? super and ? extends, read What is PECS?. KeyExtractor is the parameter you pass in, such as x -> x.getName(), that should answer the question of "when given a T, what is a U that you want to compare by?". ![]() The > part first declares two generic type parameters - T is what the comparator compares ( Person in the above case), and U is the type that you are actually comparing ( String in the above case), hence it extends Comparable. We tend to think about what things to sort by, rather than how exactly to compare two things, and the exact number to return depending on the comparison result.Īs for the declaration for comparing: public static > Comparator comparing( The latter is clearly much more concise and intuitive. (a, b) -> a.getName().compareTo(b.getName()) Ĭparing(x -> x.getName()) // or Person::getName Given two people, a and b, the comparison result between a and b is theĬomparison result between a's name and b's name And that is what you can do with the keyExtractor argument of paring. However, a much more convenient way to do this is to specify "given a thing x, what part of x do you want to sort by?". The a and b is why it has 2 lambda parameters, and you return an integer indicating your answer to that question. When sorting things, you are supposed to specify "given two things a and b, which of them is greater, or are they equal?" using a Comparator. Yes, you can sort of think of it like that. Is paring() used for converting a single argument lambda expression to a double argument? ![]() is paring() used for converting a single argument lambda expression to a double argument one or does it has some other use as well.Īlso please explain the part of the below function declaration. So I am able to understand the first lambda expression but I wonder the use of paring(s->s) i.e. The sorted method takes a Comparator as a argument. Projects.stream().sorted(paring(s->s)).forEach(s->(s)) As far as I understand Comparator is a functional interface used to compare 2 objects with int compare(T o1, T o2) as the abstract function that takes two argument.īut there is also a function paring(s->s) that can take a lambda function with only one input parameter.įor Example to sort a Collection using streams List projects=Arrays.asList("abc","def","sss","aaa","bbb")
0 Comments
Leave a Reply. |