Collections 和 Collection,名字看起来很相似,但实际上它们是 两个完全不同的东西 !不过,它们确实有一些关系,主要体现在 Collections是为了操作 Collection接口的集合类提供了很多常用的工具方法 。
| 方法 | 作用 | 示例 |
|---|---|---|
sort() |
对 List 排序 | Collections.sort(list); |
reverse() |
翻转 List | Collections.reverse(list); |
shuffle() |
打乱 List | Collections.shuffle(list); |
swap() |
交换元素 | Collections.swap(list, i, j); |
max() / min() |
求最大 / 最小元素 | Collections.max(list); |
frequency() |
某元素出现次数 | Collections.frequency(list, "apple"); |
copy() |
拷贝列表 | Collections.copy(dest, src);(dest 必须有足够容量) |
fill() |
用一个值填充整个列表 | Collections.fill(list, 0); |
binarySearch() |
二分查找(需已排序) | Collections.binarySearch(list, target); |
replaceAll() |
替换指定值 | Collections.replaceAll(list, oldVal, newVal); |
rotate() |
旋转列表(整体右移) | Collections.rotate(list, k); |
其中要倒序排序的话,可以使用:Collections.sort(list, Collections.reverseOrder());
并且排序的类型如果是自定义类型,同样要重写一下特定的比较器,如下所示:
Collections.sort(rec, new Comparator<String>() {
public int compare(String word1, String word2) {
return cnt.get(word1) == cnt.get(word2) ? word1.compareTo(word2) : cnt.get(word2) - cnt.get(word1);
}
});