我有一个数组列表,其值为:
was - 2 它 - 2 该 - 2 次 - 2
的 - 2
最佳 - 1 最差 - 1
此列表刚刚按字符串末尾的计数值排序(使用选择排序),但现在我想按字母顺序对具有相同计数的单词进行排序,我不知道该怎么做。
所以预期的输出应该是
[it - 2, of - 2, the - 2, times - 2, was - 2, best - 1, worst - 1]
概述
对于排序,始终有两种方法:
- 使班级
Comparable
- 使用
Comparator
我假设你的值是某种类,比如
public class Entry {
private final String text;
private final int count;
// getters, constructor, toString, ...
}
<小时 />可比
对于第一个选项,只需让您的类使用首先使用count
的逻辑实现Comparable
,然后,如果相等,则考虑text
。
public class Entry implements Comparable<? extends Entry> {
private final String text;
private final int count;
// getters, constructor, toString, ...
@Override
public int compareTo(Entry other) {
int countResult = -1 * Integer.compare(count, other.count);
return countResult != 0 ? countResult : text.compareTo(other.text);
}
}
然后只需对您的收藏进行排序:
Collections.sort(entries);
-1 *
是按计数降序排序,而不是默认的升序。
比较器
您可以使用Comparator
执行相同的操作。幸运的是,自Java 8以来,我们得到了一些不错的辅助方法,使这变得更加简单,这是代码:
Comparator<Entry> comparator = Comparator.comparingInt(Foo::getValue)
.reversed()
.thenComparing(Foo::getText);
然后你把它交给分拣机:
entries.sort(comparator);
在s+-s+
上拆分字符串,这意味着一个或多个空格字符(即s+
) 后跟-
后跟一个或多个空格字符。
对数字(第二部分)的降序执行第一级比较,然后对第一部分的升序执行第二级比较。
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String args[]) {
List<String> list = new ArrayList<>(
List.of("was - 2", "it - 2", "the - 2", "times - 2", "of - 2", "best - 1", "worst - 1"));
list.sort(new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
String[] s1Parts = s1.split("\s+-\s+");
String[] s2Parts = s2.split("\s+-\s+");
int i = Integer.compare(Integer.parseInt(s2Parts[1]), Integer.parseInt(s1Parts[1]));
if (i != 0) {
return i;
}
return s1Parts[0].compareTo(s2Parts[0]);
}
});
System.out.println(list);
}
}
输出:
[it - 2, of - 2, the - 2, times - 2, was - 2, best - 1, worst - 1]
注意:如果每个字符串的两个部分总是用-
分隔,则可以拆分为s1.split(" - ");
。
1:- With Use Comparator
Collections.sort(creatorIdList, (Object o1,Object o2)->{
//return 0;
});