创建 Comparator<T>
最惯用的方法是什么? Java 8 中的实例,它根据给定 List
中的相对索引定义对象的排序。但仍然将列表中不存在的对象定义为列表中的对象“之后”? — 如果我简单地使用 List.indexOf(Object)
,不在列表中的对象将始终在列表中的对象之前,因为 -1
返回所有不在列表中的对象,该对象小于任何“true”索引:
final List<String> ordering = Arrays.asList("foo", "bar");
final Comparator<String> orderingComparator = Comparator.comparingInt(ordering::indexOf);
final String str1 = "foo";
final String str2 = "baz";
final String msg;
final int cmp = orderingComparator.compare(str1, str2);
if (cmp < 0) {
msg = String.format("Element \"%s\" is ordered before \"%s\".", str1, str2);
} else if (cmp > 0) {
msg = String.format("Element \"%s\" is ordered after \"%s\".", str1, str2);
} else {
msg = String.format("Element \"%s\" is equal to \"%s\".", str1, str2);
}
System.out.println(msg);
这会打印
Element "foo" is ordered after "baz".
而我想要的行为会打印
Element "foo" is ordered before "baz".
最佳答案
您可以将 indexOf
的结果威胁为无符号整数。那么 -1
将是最大值并放置在其他值之后。
这可能是最易读的方法(尽管每个索引都会被装箱):
Comparator.comparing(ordering::indexOf, Integer::compareUnsigned)
这是一个更快的替代方案,可以避免装箱:
Comparator.comparingInt(s -> ordering.indexOf(s) + Integer.MIN_VALUE)
关于Java 8 : Idiomatically creating a Comparator for ordering objects based on their index in a List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41122819/