java—当列表中有空值时如何排序

evrscar2  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(358)

我是java新手,但我正在尝试将c#转换为java,在这里我面临排序方面的一些问题。
因为我在上面做了5次循环来生成结果,所以当我的代码第一次出现在这里时 result 大概是 [5,2,3], [null], [null], [null], [null] .
所以我想把它分类 result = [2,3,5], [null], [null], [null], [null] . 但当我想这么做的时候,我会 NullPointerException . 我猜这是因为我的列表包含空值。
java代码:

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

如果我能在兰姆达做到:

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

那么如何在java中解决这个问题呢?

gstyhher

gstyhher1#

如果它是java对象的集合,则可以实现 Comparable 用于计算 .sort() 对象的名称。
不过幸运的是,streamapi已经有了一些有用的内置方法以及comparator。
例如,对于你的字符串,我写了:

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

相关问题