Search code examples
javasortingnullpointerexceptioncomparator

Java Comparator.nullsLast and Comparator.nullsFirst not working as expected


I have the following method, which throws NPE in sort() when I am trying to sort by a field which is null in the list :

private List<MobileSearch> sortAscAndDesc(final MobilesPostResponse mobilesPostResponse,
            final String[] split,
            final Comparator<MobileSearch> comparing) {

    final var direction = getDirection(split);

    final var modifiableList = new ArrayList<MobileSearch>(mobilesPostResponse.getMobiles());

    final var comparator = direction.equals(Constants.ASC)
            ? comparing.thenComparing(Comparator.nullsLast(comparing))
            : comparing.thenComparing(Comparator.nullsFirst(comparing.reversed()));

    modifiableList.sort(comparator);
    return modifiableList;
}

A comparator is passed as a parameter which is using several keyExtractors. You can see below some method calls :

final var sortedList = sortAscAndDesc(mobilesPostResponse, split, Comparator.comparing(MobileSearch::getMsisdn));

final var sortedList = sortAscAndDesc(mobilesPostResponse, split, Comparator.comparing(MobileSearch::getAssignedProfile));

All I want is to avoid getting NPE when applying the modifiableList.sort() in EVERY case, but with my piece of code I can not achieve it. Any ideas?


Solution

  • You are using the comparing comparator on the null values by using comparing.thenComparing(...) and then only you use the Comparators.nulls...(..). You just need the Comparator.nulls...(..) like this :

    private List<MobileSearch> sortAscAndDesc(final MobilesPostResponse mobilesPostResponse,
            final String[] split,
            final Comparator<MobileSearch> comparing) {
    
        final var direction = getDirection(split);
    
        final var modifiableList = new ArrayList<MobileSearch>(mobilesPostResponse.getMobiles());
    
        final var comparator = direction.equals(Constants.ASC)
                ? Comparator.nullsLast(comparing)
                : Comparator.nullsFirst(comparing.reversed());
    
        modifiableList.sort(comparator);
        return modifiableList;
    }