Comparator#compareTo returns an int; while getTime is obviously long.
It would be nicer written like this:
.sort(Comparator.comparingLong(Message::getTime))
Answer from Eugene on Stack OverflowComparator#compareTo returns an int; while getTime is obviously long.
It would be nicer written like this:
.sort(Comparator.comparingLong(Message::getTime))
Lambda
The lambda can be seen as the shorthand of somewhat cumbersome anonymous class:
Java8 version:
Collections.sort(list, (o1, o2) -> o1.getTime() - o2.getTime());
Pre-Java8 version:
Collections.sort(list, new Comparator<Message>() {
@Override
public int compare(Message o1, Message o2) {
return o1.getTime() - o2.getTime();
}
});
So, every time you are confused how to write a right lambda, you may try to write a pre-lambda version, and see how it is wrong.
Application
In your specific problem, you can see the compare returns int, where your getTime returns long, which is the source of error.
You may use either method as other answer method, like:
Long.compare(o1.getTime(),o2.getTime())
Notice
- You should avoid using
-inComparator, which may causes overflow, in some cases, and crash your program.
Videos
The cleanest way would be:
CopyArrays.sort(months, Comparator.comparingInt(String::length));
or, with a static import:
CopyArrays.sort(months, comparingInt(String::length));
However, this would work too but is more verbose:
CopyArrays.sort(months,
(String a, String b) -> a.length() - b.length());
Or shorter:
CopyArrays.sort(months, (a, b) -> a.length() - b.length());
Finally your last one:
CopyArrays.sort(months,
(String a, String b) -> { return Integer.signum(a.length() - b.length()) };
);
has the ; misplaced - it should be:
CopyArrays.sort(months,
(String a, String b) -> { return Integer.signum(a.length() - b.length()); }
);
You're looking for this:
CopyArrays.sort(months, (a, b) -> Integer.signum(a.length() - b.length()));
public static int longestStrChain(String[] words) {
Arrays.sort(words, (a, b) -> a.length() - b.length());
HashMap<String, Integer> dp = new HashMap<>();
int max_chain = 0;
for (String word : words) {
dp.put(word, 1);
for (int i = 0; i < word.length(); i++) {
String prev_word = word.substring(0, i) + word.substring(i + 1);
if (dp.containsKey(prev_word)) {
dp.put(word, Math.max(dp.get(word), dp.get(prev_word) + 1));
}
}
max_chain = Math.max(max_chain, dp.get(word));
}
return max_chain;
}Can someone help me understand how doesArrays.sort(words, (a, b) -> a.length() - b.length()); actually work? they said that it's for sorting String array, descending order. I don't even know how this
does work i use the debugging tool and seems like it's looping through the array, i was fine with the for-each-loop sorting until this came in.
for(int i = 0; i<words.length;i++) {
for (int j = i; j < words.length; j++) {
if (words[j].length()<words[i].length()){
swap(j,i,words);
}could someone please explain this to me? the Array.sort is looping too so maybe it's the same?