How to sort an array of objects containing null elements?

java sort array of objects by property
javascript sort array with null values
java 8 sort list with null values
sorting with null values
java sort array of objects by field
how to sort array with null values java
java 8 sort list of objects with null values
array sort null javascript

In my program an array fClasses of fixed length [7] of objects is created, each object is a class FClass that contains 3 Strings, an int, and an int[]. These values are read from a .txt file and added to a specific index of the array based on the value of the int. There are less entries in the .txt file then there are indices in the array so the array ends up looking something like this:

fClasses[0] { str1, str2, str3, int1, int [] {1,2,3,4,5}}
fClasses[1] { str1, str2, str3, int1, int [] {1,2,3,4,5}}
fClasses[2] { str1, str2, str3, int1, int [] {1,2,3,4,5}}
fClasses[3] null
fClasses[4] null
fClasses[5] { str1, str2, str3, int1, int [] {1,2,3,4,5}}
fClasses[6] { str1, str2, str3, int1, int [] {1,2,3,4,5}}

Later in the program I need to sort the array based on the average of the ints in the int[]. I have a working method to return this but when I try to sort the array using compareTo and Arrays.sort I get a long list of errors starting with these:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source)
    at java.util.ComparableTimSort.sort(Unknown Source)
    at java.util.Arrays.sort(Unknown Source)
    at FProg.sortClasses(FProg.java:228)

My compareTo method looks like this and it's located in a class that implements Comparable:

public int compareTo(FClass other) 
{
    if (other == null || this.avg == other.avg)
    {
        return 0;
    }
    else if (this.avg < other.avg)
    {
        return -1;
    }
    else
    {
        return 1;
    }

}

And I'm trying to call this method to do the sorting:

public void sortClasses()
{
    Arrays.sort(fClasses, 0, MAX_CLASSES);
}

I have tested it with a .txt file that contains enough entries to fill the array and the sort works correctly in that case, so I believe the problem I'm having is that my sort method can't sort an array with null elements in it. Is there any way this can be achieved?

You need your own Comparator implementation and check for nulls and return 0

 Arrays.sort(fClasses, new Comparator<FClass>() {
    @Override
    public int compare(FClass o1, FClass o2) {
        if (o1 == null && o2 == null) {
            return 0;
        }
        if (o1 == null) {
            return 1;
        }
        if (o2 == null) {
            return -1;
        }
        return o1.compareTo(o2);
    }});

How to sort an array of objects containing null elements?, You need your own Comparator implementation and check for nulls and return 0. Arrays.sort(fClasses, new Comparator<FClass>()  Whenever we try to sort elements with null values using the sort method it throws an exception. The sort() method of the Arrays class also accepts a Comparator along with the array. Using comparator, you need to specify the order in which the elements need to be sorted. Using this

Using Java 8, you can easily build the comparator you need:

Arrays.sort(fClasses, Comparator.nullsFirst(Comparator.naturalOrder()));

Use nullsLast instead if that's what you want, of course.

Comparator nullsLast() method in Java with examples , Return value: This method returns a comparator that considers null to be greater than non-null and compares non-null objects with the supplied Comparator. Below programs of an array of names. // also contains nulls List<User> list. = Arrays.asList(u1, u2, u3, null , u4);. Collections.sort(list,. Comparator.nullsLast(. In my program an array fClasses of fixed length [7] of objects is created, each object is a class FClass that contains 3 Strings, an int, and an int[]. These values are read from a .txt file and added to a specific index of the array based on the value of the int.

You have to create a Comparator<FClass>, rather than use a Comparable<FClass>.

public class FClassComparator implements Comparator<FClass> 
{
    public int compare(FClass left, FClass right) {
        // Swap -1 and 1 here if you want nulls to move to the front.
        if (left == null) return right == null ? 0 : 1;
        if (right == null) return -1;
        // you are now guaranteed that neither left nor right are null.

        // I'm assuming avg is int. There is also Double.compare if they aren't.
        return Integer.compare(left.avg, right.avg); 
    }
}

Then call sort via:

Arrays.sort(fClassArray, new FClassComparator());

Natural Order Comparators in Java, We will also cover how to handle null values in a Collection or array. naturalOrder() that returns a comparator that compares objects in natural order. Above code will throw a NullPointerException if specified array contains any null value. If the result is positive b is sorted before a. If the result is 0 no changes are done with the sort order of the two values. Example: The compare function compares all the values in the array, two values at a time (a, b). When comparing 40 and 100, the sort() method calls the compare function(40, 100).

With Apache Commons Collections 4 you can use ComparatorUtils to do that:

Collections.sort(arr, ComparatorUtils.nullLowComparator(ComparatorUtils.NATURAL_COMPARATOR));

How To Sort Objects In Java, Here is a simple tutorial that explains how to sort in Java. In this article, I will be mainly focusing on sorting ArrayList, HashSet, if (o == null || getClass() != o. access to a sequence of elements, like arrays or generator functions. Nevertheless, it does not contain, nor could it, every single operation that  Introduction to JavaScript array sort method. The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort() method also sorted the array that you pass in. By default, the sort() method uses string Unicode code points to determine the order of the elements.

By importing the org.apache.commons.collections.comparators package of the Apache 2.1.1 Release library, I'm able to sort a list, such as an ArrayList<String>, using the NullComparator as the second argument of the Collections.sort() method, as follows:

ArrayList<String> list = new ArrayList<String>();
list.add("foo");
list.add("bar");
list.add("baz");
list.add(null);

// Sort the list
Collections.sort(list, new NullComparator(true));

System.out.println(list);
// outputs:
// [bar, baz, foo, null]

The thing I like about this approach is that the NullComparator has an overload constructor which allows you to specify whether you want null to be considered a high value or a low value, which seems pretty intuitive to me.

NullComparator(boolean nullsAreHigh)

Hope this helps someone!

Sorting a List having null values with Comparator's nullsFirst, Sorting a list of Custom objects with nulls without using nullsFirst – Solving package com.blogspot.javasolutionsguide;. import java.util.Arrays;. Basic Array Sorting. By default, the JavaScript Array.sort function converts each element in the array that needs to be sorted into a string, and compares them in Unicode code point order.

Arrays (Java Platform SE 8 ), This class contains various methods for manipulating arrays (such as sorting and (For example, the algorithm used by sort(Object[]) does not have to be a Copies the specified array, truncating or padding with nulls (if necessary) so the  In this tutorial we will see how to sort an ArrayList of Objects by property using comparable and comparator interface. If you are looking for sorting a simple ArrayList of String or Integer then you can refer the following tutorials – We generally use Collections.sort () method to sort a simple array list.

Arrays (Java SE 11 & JDK 11 ), This class contains various methods for manipulating arrays (such as sorting and (For example, the algorithm used by sort(Object[]) does not have to be a Copies the specified array, truncating or padding with nulls (if necessary) so the  ArrayList sort() – Sort list of objects by field Comparators are most useful when we want to sort a given list of objects – but not in natural order . For example, a list of employees should be sorted on their employee id, naturally.

How not to sort an array in JavaScript, Recently I was working with array of items in JavaScript that were not JavaScript has a sort method available on Array objects and running it will you might come across is if you find yourself with an array containing null . contains(element) method does not take null argument, and will throw NullPointerException is null is passed in the method. 1.1. Method Syntax. Method takes one argument of type Object, whose presence in this list is to be tested. Method returns true – if list contains the argument element.

Comments
  • shouldn't o1 == null return -1, because a null value means that it has less significance than o2 which actually has a value