I know there are many similar questions about the same issue. However, I've tried the solutions provided and none worked for me. I am 100% sure it is something basic I am missing, but I am not able to find what is wrong, hence asking it here...
I have a custom object like this:
public class ClassA {
private int id;
private Integer min1;
private Integer min2;
}
In another class (ClassB) I have a list of ClassA objects that I need to sort. First items should be those who have a lower value in any of the min properties. In case two objects have the same value, then does not matter which one goes first. For example, if I have these objects:
| ID | min1 | min1 |
|---|---|---|
| 1 | 10 | null |
| 2 | null | 30 |
| 3 | 80 | null |
| 4 | 23 | null |
| 5 | 10 | null |
Order should be (ID): 1, 5, 4, 2, 3.
To achieve this I have a method that returns a Comparator:
public static Comparator<ClassA> compareMins(Function<ClassA, Integer> min) {
return Comparator.comparing(minuto, Comparator.nullsLast(Comparator.naturalOrder()));
}
In ClassB I get the Comparator and sort the list as follows:
Comparator<ClassA> comparator = ClassA.compareMins(ClassA::getMin1)
.thenComparing(ClassA::getMin2);
lista.sort(comparator);
However, it is throwing a NullPointerException when comparing objects ID 1 and 5. I guess that as min1 has the same value, it tries to compare min2, which are null, and hence, throwing this exception. However, I am unable to find a solution to this. Any help would be really appreciated.
It looks like you've forgotten to use your nulls comparator
compareMinsa second time:As you have it now, using
.thenComparing(ClassA::getMin2), would evaluate the two instances ofmin2and would calla.min2.compareTo(b.min2)rather than the nulls friendly check you have created incompareMins. HenceNullPointerException.Also, you have mixed
minandminutoin the declaration ofcompareMins, this could be source of NPE => replaceminutowithmin.}