按字母顺序对列表中的特定值排序(如果存在)

Spi*_*ina 5 java sorting java-8

我正在寻找满足以下测试用例的比较器最可读的定义:

@Test
public void testComparator() {
    List<String> toSort = Lists.newArrayList("a", "b", "c", "d", "e", "f");
    Collections.shuffle(toSort);
    Comparator<String> theSolution = ???; 
    Collections.sort(toSort, theSolution);
    System.out.println(toSort); // Prints [c, a, b, d, e, f]
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试过使用Guava的Ordering定义的比较器,如下所示:

Ordering.explicit("c").thenComparing(Ordering.natural());
Run Code Online (Sandbox Code Playgroud)

但是,显式引发了未枚举的项的异常.所以解决方案失败了.有什么建议?

ken*_*ytm 4

您可以显式编写比较函数,例如

Comparator<String> theSolution = Comparator.comparing(a -> a.equals("c") ? "" : a);
// treat "c" as the same as the empty string "" when sorting which will be ranked first.
Run Code Online (Sandbox Code Playgroud)

  • 仅当数组中没有空字符串时才有效。 (2认同)