Reputation: 369
I am using java version 1.8, which supports lambda expressions.
I am trying to sort a stream by a custom comparator, but I am getting a ClassCastxception:
public class A {
private String type;
private String ip;
private String originSubId;
public A(String type, String ip, String originSubId) {
this.type = type;
this.ip = ip;
this.originSubId = originSubId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getOriginSubId() {
return originSubId;
}
public void setOriginSubId(String originSubId) {
this.originSubId = originSubId;
}
}
Comparator<A> defaultComparator = Comparator.comparing(A::getType)
.thenComparing(A::getIp).thenComparing(A::getOriginSubId);
Set<A> entities = new HashSet<>();
entities.stream().map(e -> convertToB(e)).sorted(defaultComparator)
.collect(Collectors.toCollection(TreeSet::new));
Error: java.lang.ClassCastException: A cannot be cast to java.lang.Comparable
What I am doing wrong?
Upvotes: 0
Views: 497
Reputation: 73558
You can't collect to a "plain" TreeSet
like that because it requires that the elements are either Comparable
or that the TreeSet
gets a custom Comparator
on creation. You also don't need to sort in the stream, as TreeSet
performs sorting on insertion. Your convertToA()
method looks suspect too, is it converting A
-> A
?
You would need something like the following
entities.stream().map(e -> convertToA(e))
.collect(Collectors.toCollection(() -> new TreeSet(customComparator)));
If your conversion method isn't needed, you can just forget the whole stream and do
Set<A> tree = new TreeSet<>(customComparator);
tree.addAll(entities);
Upvotes: 1