我正在寻找满足以下测试用例的比较器的最易读的定义:
@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]
}
我试过使用 Guava 的 Ordering 定义的比较器,如下所示:
Ordering.explicit("c").thenComparing(Ordering.natural());
但是,对于未枚举的项,显式会抛出异常。所以那个解决方案失败了。有什么建议吗?
最佳答案
你可以显式地写一个比较函数,例如
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.
关于java - 按字母顺序对列表进行排序,头部有特定值(如果存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39091954/