zk419
zk419

Reputation: 13

How to do sorting when I have null value in a list

I'm new in Java but I'm trying convert C# to Java and here I face some problem regarding sorting.

Since I'm doing a 5 times loop at above to generate the result, so when my code first time come in here, the resultwill be something like [5,2,3], [null], [null], [null], [null].

So I want to sort it become result = [2,3,5], [null], [null], [null], [null]. But then when I'm trying to do this, I'll hit NullPointerException. And I guess it is because my list contains null value.

Java Code:

Arrays.sort(result); 
String resultSorting = Arrays.toString(result);
result[j] = String.join(",", resultSorting);

And if C# I can do in lambda:

var resultSorting = result[j].Split(',').OrderBy(x => x).ToList();
result[j] = string.Join(",", resultSorting);

So how to solve this in Java?

Upvotes: 0

Views: 1405

Answers (2)

zk419
zk419

Reputation: 13

I have found a solution to solve my problem.

Before sort the element of the result, I do split the comma for my result element so that it will only do sorting for the element instead of whole array.

//Example of my result
result = [2,5,3], [null], [null], [null], [null];

String tempResult = result[j].replaceAll(",", ""); //After split the comma, result will become [253] instead of [2,5,3], [null], [null], [null], [null];
String[] resultSplitComma = tempResult.split("");
Arrays.sort(resultSplitComma);
String resultSorting = Arrays.toString(resultSplitComma);
result[j] = String.join(",", resultSorting);

And here I am very grateful to everyone who are trying to help me.

PS: This is the only solution I can think of at the moment. So if anyone still have any better solution, feel free to comment to let me learn more :)

Upvotes: 0

jden
jden

Reputation: 2288

If it were a collection of java objects, you can implement the Comparable interface which is used to calculate the .sort() of the objects.

Luckily though, the Stream API already has some useful built in methods along with Comparator.

For your strings for example I've written this:


@Test
@DisplayName("Sort Array of Strings with Nulls First or Last")
void sorty(){

    final String[] unsortedArray = {"Bob",null,"Alice",null,"Charlie","Emma",null,null,"Dave"};

    //To List with Stream, Sort using Comparator but with nulls first then collect to String list.
    final List<String> sortedArray = Arrays.stream(unsortedArray)
                .sorted(Comparator.nullsFirst(String::compareToIgnoreCase))
                .collect(Collectors.toList());

    //Assertions
    String[] expectedResult = {null,null,null,null,"Alice","Bob","Charlie","Dave","Emma"};
    Assertions.assertEquals(Arrays.asList(expectedResult),sortedArray);
    Assertions.assertNotEquals(Arrays.asList(unsortedArray),sortedArray);

    //Or using nullsLast:

    //To List with Stream, Sort using Comparator but with nulls last then collect to String list.
    final List<String> sortedArrayNullsLast = Arrays.stream(unsortedArray)
                .sorted(Comparator.nullsLast(String::compareToIgnoreCase))
                .collect(Collectors.toList());

    //Assertions
    String[] expectedResultNullsLast = {"Alice","Bob","Charlie","Dave","Emma",null,null,null,null};
        Assertions.assertEquals(Arrays.asList(expectedResultNullsLast),sortedArrayNullsLast);
        Assertions.assertNotEquals(Arrays.asList(unsortedArray),sortedArrayNullsLast);
        
        
    //PS: You can instead of Collect to List of Strings in the Stream to an array instead...

    //To List with Stream, Sort using Comparator but with nulls last then collect to String list. I just did
    // to list to compare them in the assertion tests.
    final String[] sortedArrayNullsLastAsArray = Arrays.stream(unsortedArray)
                .sorted(Comparator.nullsLast(String::compareToIgnoreCase))
                .toArray(String[]::new);
    }

Upvotes: 1

Related Questions