Skip to content
Advertisement

How to Sort List based on Inner Object’s property in java 8

I have classes structure similar to:

JavaScript

I have two different tables Source and Target, and after joining them I am getting four columns in the query output. I am constructing Response object using values of these four columns. I have data in Response object with these 4 properties sourceId, sourceName, targetId, targetName. I can have sourceId, sourceName same on the multiple rows but targetId, targetName will always be different.

I grouped all the target objects into the List for which source is the same.

JavaScript

But sometimes reponse from database cannot be sorted and even though it is sorted and I have used LinkedHashmap::new then also my final output List<FinalResponse> finalResponses is not sorted. I wanted my final output to be sorted as per sourceId, so I did:

JavaScript

It is working fine for non null values but if I have source(sourceId=null,sourceName=null) on multiple rows then I am getting NullPointerException. What is the best approach to Sort Collection based on Source Object’s sourceId property ?

Advertisement

Answer

Comparator.nullsLast or Comparator.nullsFirst should be applied to handle possible null values in the compared items:

JavaScript

or like this:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement