sort by nullable field saying the item's position

how to sort array with null values
java stream sort with null values
java 8 sort list with null values
django order by null last
how to sort list with null java
sort list based on another list java
django order by multiple fields
java 8 sort list of objects descending

I need to sort my array of object in custom way. Let's say I have two field in my objects – priority (nullable) and createdAt (non-nullable). The priority field says at which position the item should be. It can be null, however. In that case we should sort taking into consideration createdAt field (with descending order).

Let me explain it with example. For example my objects would be:

Object0: priority: null, createdAt: 2018-12-01
Object1: priority: 1,    createdAt: 2018-12-02
Object2: priority: 5,    createdAt: 2018-12-03
Object3: priority: null, createdAt: 2018-12-04
Object4: priority: null, createdAt: 2018-12-05
Object5: priority: 2,    createdAt: 2018-12-06
Object6: priority: null, createdAt: 2018-12-07

The final order should be:

  1. Object1 (by its priority)
  2. Object5 (by its priority)
  3. Object6 (filling left positions by createdAt desc)
  4. Object4 (filling left positions by createdAt desc)
  5. Object2 (by its priority)
  6. Object3 (filling left positions by createdAt desc)
  7. Object0 (filling left positions by createdAt desc)

How could I achieve my goal? Is there any out-of-the-box comparator ready?

EDIT: I think we can use that class:

public class MyObject {
   Integer priority;
   LocalDateTime createdAt;
}

sort by nullable field saying the item's position, I need to sort my array of object in custom way. Let's say I have two field in my objects – priority (nullable) and createdAt (non-nullable). The priority field says at​  The above queries sort the results for nullable column (commission). If you would like to sort non-NULL values in ascending and descending order and place the NULL values either first or last, you can use sub-queries with case expression. Using a case expression, you can flag NULL values, and non-NULL values.

No, don’t use a comparator for this, or more precisely, not for the whole job. A comparator’s job is to compare two objects and tell the order between those two. It will not be suited for detecting gaps in the priority sequence.

Instead, assuming that priorities are integral and unique I suggest you use an array and a kind of radix sort for the objects with defined priorities. Priority 1 goes into array index 1, priority 2 index 2, etc. The objects with null priority are sorted with a comparator on creation date descending and are then filled into the array indices that are still null (except index 0, I guess).

By "assuming that priorities are integral and unique" I mean that you don’t risk two objects with priority 3 or an object with priority 2.44.

I might use a stream and Collectors.partitioningBy to separate the objects with priorities from those without priority, but there are other ways to do, of course.

I’d hand code this. I have never heard of any ready-made solution for it. Searching never harms, but I’d be surprised to find one. On the other hand, not that many lines of code will be needed.

BTW use LocalDate for your dates since they don’t have time of day (not LocalDateTime).

Mastering Microsoft Visual Basic 2008, The ISNULL() SQL function accepts two arguments: a column name and a string. The function returns the value of the specified column, unless this value is Null, in which case it Let's say you want to see the list of the 10 top-selling products. Retrieve the products and the number of items sold for each item, order the rows​  Since true values are sorted to the end in an ascending sort, the dates with values will be first in the sort order, then the null values. The secondary sort (ThenBy), then sorts by the LastOrderDate. This provides the list with the rows in ascending date order, but with the null values last in the list.

One possible way (not very sure about the efficiency) of doing that involving streams could be :

List<CustomObject> customObjectList = new ArrayList<>(); // your initialisation;

// list of only those objects whose priority is null sorted descending by createdAt
List<CustomObject> nullValues = customObjectList.stream()
        .filter(a -> a.getPriority() == null)
        .sorted(Comparator.comparing(CustomObject::getCreatedAt).reversed())
        .collect(Collectors.toList());

// remaining non null priority objects sorted by priority ascending
List<CustomObject> remainingValues = customObjectList.stream()
        .filter(a -> a.getPriority() != null)
        .sorted(Comparator.comparing(CustomObject::getPriority))
        .collect(Collectors.toList());

// final list of same size as initial
List<CustomObject> finalList = new ArrayList<>(customObjectList.size());

// set the priority based indexes first
remainingValues.forEach(a -> finalList.add(a.getPriority(), a));

// iterate through the final list and fill in the empty slots 
// while popping(`remove(0)`) the element from list sorted descending by createdAt
IntStream.range(0, finalList.size())
        .filter(i -> finalList.get(i) == null)
        .forEach(i -> finalList.add(i, nullValues.remove(0)));

Note: Few assumptions here are - There is 0 based priority set in the list. - The non-null priority values are the exact indexes in the finalList

Sorting a list in Java with null values – Memoirs of a Software , You bring all your Object oriented skills to the table, create a The code says, use natural order for sorting phoneBrand fields and if you  The EndDate column was used for ascertaining the main sort order however this posed a problem with current jobs as they do not yet have an end date. Luckily achieving this with Lambda (or linq) is very straight forward. The following code simply uses DateTime.MaxValue if the actual DateTime is null:

Sorting querysets with NULLs in Django, This is particularly strange if, say, you want a list of items sorted by most as the secondary sort field, safe in the knowledge that all the NULL s  Let’s start simple and sort the data by the “Atomic Number” column. Start by selecting the column (you can include the header row if your data has one). Now navigate to the “Sort & Filter” drop-down and select either the first or second option.

Data and File Structure (For GTU), 2nd Edition, Searching in a Sorted List The process of searching an item into a sorted (​ascending NULL //traversing up to the last node If item < ptr->info // comparing item with the For this, three pointer variables (say, save, ptr and temp) are used​. The links between nodes are reversed by making the next field of the node pointed  The new features that support nullable reference types help you find and fix potential errors in how you handle null values in your code. Enabling the nullable annotation context allows you to express your design intent: some variables should never be null, other variables may contain null values.

Sorting a List having null values with Comparator's nullsFirst, Check our article explaining how we can sort a list of items when few of the items are null in the list using Java 8. development field for more than 10 years in Java/J2EE technologies. So if you want to sort ,say your list. Nullable types are a feature of some programming languages which allow the value to be set to the special value NULL instead of the usual possible values of the data type.In statically-typed languages, a nullable type is an option type, while in dynamically-typed languages (where values have types, but variables do not), equivalent behavior is provided by having a single null value.

Comments
  • Can you give the class related to ?
  • I don't have that class to be honest. My case is more comples and here I reduced it to the minimum. I will edit my post however providing minimum class.
  • Why do object6 and object4 go between object5 and object2? You can easily sort with your own comparator lambda, but your algo isn't clear to me.
  • Object5 has priority 2, so it goes to position 2. Object2 has priority 5, so it goes to position 5. When we have all objects at theirs positions we fill left spaces in array using objects sorted by createdAt. I hope it will be more clear now.
  • You can't sort that way, because you says that you need the priotity to be the index and this is not how it works, you can only compare element between them, before/after/equals
  • Yes, that was what I meant. :-) You may need to take into account that the max priority may be greater than the number of objects, I don’t know, the asker should know.
  • Ok. So I know there's no comparator for that. It makes sense :) Do you know any ready solution for this?
  • As I thought finalList.set(a.getPriority(), a) throws a java.lang.IndexOutOfBoundsException: Index: 1, Size: 0, change set by an add does change the problem
  • @azro Okay didn't test this one, updated to using add.
  • f*** my mind always forget the "not" ... brain too quick for hand, "change to add does NOT change the problem" don't know how to fix it
  • @azro Okay, let me get back to it with a better tested code, mostly an initialisation of the list would be required if that's the case.