gpt4 book ai didi

java - 按字母顺序对列表进行排序,头部有特定值(如果存在)

转载 作者:搜寻专家 更新时间:2023-10-31 19:37:14 24 4
gpt4 key购买 nike

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

@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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com