简体   繁体   中英

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 result will 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?

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);
    }

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:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM