I'm iterating all Student data using natural sorting method of java 8 sorted(). While iterating student data, get exception in IDE console class com.java8.Student cannot be cast to class java.lang.Comparable. My StreamStudent.java file is inside com.java8 package.
Here is my full stack trace:
Exception in thread "main" java.lang.ClassCastException: class com.java8.Student cannot be cast to class java.lang.Comparable (com.java8.Student is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')
at java.base/java.util.Comparators$NaturalOrderComparator.compare(Comparators.java:47)
at java.base/java.util.TimSort.countRunAndMakeAscending(TimSort.java:355)
at java.base/java.util.TimSort.sort(TimSort.java:220)
at java.base/java.util.Arrays.sort(Arrays.java:1307)
at java.base/java.util.stream.SortedOps$SizedRefSortingSink.end(SortedOps.java:353)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:510)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:921)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682)
at com.java8.StreamStudent.main(StreamStudent.java:72)
Here down is my code:
package com.java8;
import java.util.*;
import java.util.stream.*;
class Student{
String firstName;
String lastName;
Integer groupId;
Integer age;
// constructor and getter, setter
}
public class StreamStudent {
public static void main(String[] args) {
List<Student> stdList = new ArrayList<>();
stdList.add(new Student("Sara", "Mills", 1, 18));
stdList.add(new Student("Andrew", "Gibson", 2, 21));
stdList.add(new Student("Craig", "Ellis", 1, 23));
stdList.add(new Student("Steven", "Cole", 2, 19));
stdList.add(new Student("Andrew", "Carter", 2, 2));
System.out.println("1. Sort all student firstname by name");
List<Student> students = stdList.stream().sorted().collect(Collectors.toList());
students.forEach((s) -> System.out.println(s.getFirstName() + " " + s.getLastName() + " " + s.getGroupId() + " " + s.getAge()));
}
}
sorted(Comparator.comparingInt(Student::getAge))orsorted(Comparator.comparing(Student::getLastName, String.CASE_INSENSITIVE_ORDER)), rather than implementingComparable. As a side note, you can sort anArrayListdirectly, e.g.stdList.sort(Comparator.comparing(Student::getFirstName));without streaming/ collecting into a new list.Comparable. From documentation: "If the elements of this stream are not Comparable, a java.lang.ClassCastException may be thrown ..."