I have a list of items (MyDetail object) that I want to sort with stream sorting methods. The object has 3 fields: field1, field2, field3. I want to sort by field3 first then field2 then field1, all with reversed order. So I wrote a method sortMyList.
I have a list of unsorted items unSortedDetails as the following: myDetail1: "20180201", false, false myDetail2: "20180101", false, false myDetail3: "20180101", false, true
after sortMyList(unSortedDetails), I expect my result would be myDetail3, myDetail1, myDetail2, but the actual result is myDetail1, myDetail3, myDetail2, Why?
so if I implement Comparable for MyDetail like the following, then it works as expected. this is so strange. I could not figure out why. thanks for any help!
public List<MyDetail> sortMyList(List<MyDetail> unSortedDetails){
List<MyDetail> myDetails = unSortedDetails
.stream().sorted(Comparator.comparing(MyDetail::getField11).reversed()
.thenComparing(MyDetail::getField2).reversed()
.thenComparing(MyDetail::getField3).reversed())
.collect(Collectors.toList());
return myDetails;
}
@Setter
@Getter
public class MyDetail{
String field1;
Boolean field2;
Boolean field3;
}
@Setter
@Getter
public class MyDetail implement Comparable<MyDetail>{
String field1;
Boolean field2;
Boolean field3;
@Override
public int compareTo(MyDetail o) {
if (this == o || this.equals(o)) return 0;
if (field3) return -1;
if (o.field3) return 1;
if (!field3 && !o.field3 && field2) return -1;
if(!field3 && !o.field3 &&!field2 && o.field2) return 1;
if(!field3 && !o.field3
&&!field2 && !o.field2){
return o.field1.compareTo(field1);
}
return 0;
}
}
field*fields are of the typeString, but you're trying to treat them asbooleanconditions in your if-statements.