英文:
How to implement Comparator.compare(T o1, T o2) method
问题
private static final String[] values = { FAULT, INVALID, QUERY, SKIP, SUCCESS, NO_ACTION }
我的使用情况要求我以一种特定的方式实现Comparator.compare(T o1, T o2)
方法,以便public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp)
在比较FAULT
和INVALID
时返回FAULT
,在比较INVALID
和QUERY
时返回INVALID
,依此类推。
在这种情况下,String.compareTo()
不能起作用,因为这将导致词典排序。
英文:
private static final String[] values = {
FAULT, INVALID, QUERY, SKIP, SUCCESS, NO_ACTION }
My use case required me to implement Comparator.compare(T o1, T o2)
method in a way public static <T> T min(Collection<? extends T> coll,Comparator<? super T> comp)
returns FAULT
, when compare between FAULT
and INVALID
, returns INVALID
, when compare between INVALID
and QUERY
and so on.
String.compareTo()
wouldn’t work in this case because that would result into lexicographic ordering.
答案1
得分: 4
一个简单的实现如下:
Comparator<String> cmp = Comparator.comparingInt(Arrays.asList(values)::indexOf);
...这将会找到在你提供的 values
数组中首次出现的字符串。(如果有任何字符串不在数组中,它们会被首先返回,但看起来这并不是你的情况。)
英文:
A simple implementation here would be
Comparator<String> cmp = Comparator.comparingInt(Arrays.asList(values)::indexOf);
...which would find the string with the first appearance in the values
array you have provided here. (If any strings weren't in the array, those would be returned first, but it doesn't sound like that's the case.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论