如何实现 Comparator.compare(T o1, T o2) 方法

huangapple go评论74阅读模式
英文:

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)在比较FAULTINVALID时返回FAULT,在比较INVALIDQUERY时返回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 &lt;T&gt; T min(Collection&lt;? extends T&gt; coll,Comparator&lt;? super T&gt; 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&lt;String&gt; 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.)

huangapple
  • 本文由 发表于 2020年10月1日 03:38:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/64144625.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定