comparing and thenComparing gives compile error

Java needs to know a type of all variables. In many lambdas it can infer a type, but in your first code snippet, it cannot guess the type of s. I think the standard way to solve that problem would be to declare it explicitly: Comparator<String> c = Comparator.comparing((String s) -> s.split(“\\s+”)[0]) .thenComparingInt(s -> Integer.parseInt(s.split(“\\s+”)[1])); … Read more

How do I write a compareTo method which compares objects?

This is the right way to compare strings: int studentCompare = this.lastName.compareTo(s.getLastName()); This won’t even compile: if (this.getLastName() < s.getLastName()) Use if (this.getLastName().compareTo(s.getLastName()) < 0) instead. So to compare fist/last name order you need: int d = getFirstName().compareTo(s.getFirstName()); if (d == 0) d = getLastName().compareTo(s.getLastName()); return d;

When to use Comparable and Comparator

Use Comparable if you want to define a default (natural) ordering behaviour of the object in question, a common practice is to use a technical or natural (database?) identifier of the object for this. Use Comparator if you want to define an external controllable ordering behaviour, this can override the default ordering behaviour.

How to implement the Java comparable interface?

You just have to define that Animal implements Comparable<Animal> i.e. public class Animal implements Comparable<Animal>. And then you have to implement the compareTo(Animal other) method that way you like it. @Override public int compareTo(Animal other) { return Integer.compare(this.year_discovered, other.year_discovered); } Using this implementation of compareTo, animals with a higher year_discovered will get ordered higher. I … Read more

When should a class be Comparable and/or Comparator?

The text below comes from Comparator vs Comparable Comparable A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances. Comparator A comparator object is capable of comparing two different objects. The class is not comparing its instances, … Read more

Bad Operand error in a Movie Session Program

> is a numerical comparison operator, and according to JLS Sec 15.20.1: The type of each of the operands of a numerical comparison operator must be a type that is convertible (ยง5.1.8) to a primitive numeric type, or a compile-time error occurs. Your Time type cannot be converted to a primitive numeric type, because it’s … Read more