What is the correct way to sort a list using a Java lambda comparator, and how can I fix the type mismatch error?

I’m trying to sort a List<Message> using a lambda expression in Java 8 like this:

List<Message> messagesByDeviceType = new ArrayList<>();
messagesByDeviceType.sort((Message o1, Message o2) -> o1.getTime() - o2.getTime());

However, I’m getting compilation errors related to a type mismatch: it says it cannot convert from long to int.

I understand this has something to do with how Comparator expects the return type, but I’m not sure how to properly use a Java lambda comparator when the comparison involves long values like timestamps. What’s the right way to resolve this?

The safest and most readable way is to use the Long.compare() method, which handles long values properly without manual casting or subtraction.

messagesByDeviceType.sort((o1, o2) -> Long.compare(o1.getTime(), o2.getTime()));

Long.compare() takes two long values and returns an int result, which is exactly what Comparator needs. It avoids issues with overflow or type mismatch.

Java 8 provides utility methods that make sorting by a primitive field super clean.

If you’re sorting by a long-returning getter like getTime(), this approach is elegant:

messagesByDeviceType.sort(Comparator.comparingLong(Message::getTime));

If you’re absolutely sure the values returned by getTime() fit safely within an int range (which is rare with timestamps), you could cast them.

But this is not recommended for general use:

messagesByDeviceType.sort((o1, o2) -> (int)(o1.getTime() - o2.getTime()));