In article <53ae0af4$0$302$14726298@news.sunsite.dk>, Arne Vajh?j
(arne@vajhoej.dk) says...
Here is a simple example.
Java 7 code:
Collections.sort(lst, new Comparator<String>() {
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
});
Java 8 code:
Collections.sort(lst, (s1,s2) -> s1.length() - s2.length());
I do not see any value in the extra code in the 7 version.
I fear Java8's Lambdas may not encourage reuse so much as the Java 7
way. This does seem to be a pretty standard comparator, so I would
probably code it this way:
static final Comparator<String> COMPARE_BY_LENGTH = new Comparator<>{
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
});
Collections.sort(lst, COMPARE_BY_LENGTH);
Just because using it looks better.
Of course in Java 8 it could look like this (sorry for the bad line
breaks:
static final Comparator<String> COMPARE_BY_LENGTH
= (s1,s2) -> s1.length() - s2.length()
Collections.sort(lst, COMPARE_BY_LENGTH);
..or even implementing a more general interface.
But would people do that very often, if the original expression is so
concise? Hmm..