TreeSet通过构造方法实现自定义排序
TreeSet treeSet = new TreeSet(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return ((String) o1).length() - ((String) o2).length();
}
});
treeSet.add("bbb");
treeSet.add("a");
treeSet.add("ee");
treeSet.add("cccc");
System.out.println(treeSet);
TreeMap通过构造方法实现自定义排序
TreeMap<String, String> map = new TreeMap<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
});
map.put("aaa", "cat");
map.put("bb", "pig");
map.put("c", "pig");
System.out.println(map);
Collections工具类
- Collections是一个可以操作Set、List、Map等的工具类
- 提供了一系列静态方法对集合元素进行查询、修改和排序等操作
排序操作
- 反转list:Collections.reverse(list)
- 对集合进行随机排序: Collections.shuffle(list)
- 根据元素的自然顺序对指定集合的元素进行排序:Collections.sort(list)
- 根据指定的Comparator产生的顺序对指定的集合元素排序
Collections.sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return ((String)o1).length() - ((String)o2).length();
}
})
- swap(list, int i, int j):将指定list集合中的i和j元素交换
- Collections.max(list):根据元素的自然顺序返回给定集合中的最大元素
- Collections.max(Collection, comparator):根据Comparator指定的顺序,返回集中中最大的元素
- Collections.min(list):根据元素的自然顺序返回给定集合中的最小元素
- Collections.min(Collection, comparator):根据Comparator指定的顺序,返回集中中最小的元素
- Collections.frequency(Collection, object):返回指定集合中指定元素出现的次数
- Collections.copy(dest, list):把list中的元素拷贝到dest中
- Collections.replaceAll(list, oldVal, newVal):把list中oldVal用newVal代替