Have a look at the Java Doc for interface Comparable<T>
.
It provides a method to compare this object against another object (passed in parameter o
) of the same type (in your case: T is Simpson
)
int compareTo(T o)
Also your name
properties are already comparable, because of type String
, which implements this interface too. So you can simply delegate (as you already well did).
Supposed error
Please correct the method signature, it's currently incomplete and might be the cause of a compilation error:
@Override ( simpson) -> {
return this.name.compareTo(simpson.name);
. }
Fix issues
Give the method the same name and return type and parameters as prescribed by the interface:
public int compareTo(Simpson o) {
if (o == null || this.name == null) return -1; // could adjust to your needs to avoid NPE
return this.name.compareTo( o.name );
}
Most important: since interfaces are to be called from outside, the implemented methods must be public
!
Just lambda
Or just go by streaming with appropriate lambda expression as suggested in previous answer
simpsons.stream()
.map(s -> s.name) // map serves like delegation to name
.sorted((s1, s2) -> s1.compareToIgnoreCase(s2)) // sort previous with current element, here: names alphabetically
.forEach(System.out::print);
Difference when sorting in streams:
- use
sorted()
, not sort()
like for collections
- you can specify a
Comparator
as functional or lambda expression
- you can also sort by natural order (as illustrated in following question)
There is yet another, simpler way to sort strings lexicographically:
Java 8 Stream sorting List of String
Comparator and natural-order
You can also combine both:
(1) comparable interface, implemented by Simpson
(2) stream with functional, sorted by comparator or lambda expression (as suitable).
simpsons.stream()
.sorted((s1, s2) -> s1.compareTo(s2)) // sort previous with current Simpson ! explicit comparator passed as lambda
.forEach( s -> System.out.println(s.name) ); // print name of Simpson in new line
In the simple case, you don't need to
Or you can use intelligent sorting and ! implicitly reuse the existing natural order by replacing with .sorted()
.
Try also what happens out-of-the-box (without any compareTo ⁉️):
class Simpson {
String name;
Simpson(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
// main omitted, just the usage example:
simpsons.stream().sorted().forEach(System.out::println );
Sorting naturally would fallback to use toString
if otherwise not comparable. Same way printing uses toString
.
Does it sort correctly and print appealing❔