操作集合的工具类 Collections
- Collections 是一个操作 Set、List 和 Map 等集合的工具类。
- Collections 中提供了大量方法对集合元素进行排序、查询和修改等操作,还提供了对集合对象设置不可变、对集合对象实现同步控制等方法
排序
排序操作如下:
-
reverse(List):反转 List 中元素的顺序
// reverse 反转 List 中的元素顺序 Collections.reverse(list);
-
shuffle(List):对 List 集合元素进行随机排序
// shuffle 对 List 集合中的元素进行随机排序 Collections.shuffle(list);
-
sort(List):根据元素的自然顺序对指定 List 集合元素按升序排列
// sort(list) 根据元素自然排列顺序对 List 集合元素进行升序排列 Collections.sort(list);
-
swap(List, int, int):将指定 list 集合中的两个元素进行互换
// swap 将指定 list 集合中的两个元素进行互换 Collections.swap(list, 0,1);
-
sort(List, Comparator):根据指定的 Comparator 产生的顺序对 List 集合元素进行排序
public class Demo01 { public static void main(String[] args) { Demo02 d1 = new Demo02("zhang3",18); Demo02 d2 = new Demo02("li4",21); Demo02 d3 = new Demo02("wang5",19); Demo02 d4 = new Demo02("lao6",25); List<Demo02> list1 = new ArrayList<Demo02>(); list1.add(d1); list1.add(d2); list1.add(d3); list1.add(d4); // sort(List, Comparator) 根据指定的 Comparator 产生的顺序对 List 集合元素进行排序 Collections.sort(list1,new Demo02()); for (Demo02 demo : list1) { System.out.println(demo.name + "," + demo.age); } } } class Demo02 implements Comparator<Demo02> { String name; int age; Demo02() {} Demo02(String name,int age) { this.name = name; this.age = age; } @Override public int compare(Demo02 o1, Demo02 o2) {//根据年龄进行升序排列 if (o1.age > o2.age) { return 1; }else if (o1.age < o2.age) { return -1; }else { return 0; } } }
查找、替换
-
Object max(Collection):根据元素的自然排序,返回给定集合中的最大元素(把 max 改为 min 则返回给定集合中最小元素)
//据元素的自然排序,返回给定集合中的最大元素 System.out.println(Collections.max(list)); //据元素的自然排序,返回给定集合中的最小元素 System.out.println(Collections.min(list));
-
Object max(Collection, Comparator):根据 Comparator 指定的顺序,返回给指定集合中的最大元素(把 max 改为 min 则返回最小元素)
//根据 Comparator 指定的顺序,返回给指定集合中的最大元素 Demo02 d = Collections.max(list1, new Demo02()); System.out.println(d.name + "," + d.age); //根据 Comparator 指定的顺序,返回给指定集合中的最小元素 Demo02 dd = Collections.min(list1, new Demo02()); System.out.println(dd.name + "," + dd.age);
-
int frequency(Collection, Object):返回指定集合中指定元素的出现次数
// frequency 返回指定集合中指定元素的出现次数 System.out.println(Collections.frequency(list, "a"));
-
boolean replaceAll(List list, Object oldVal, Object newVal):使用新值替换 List 对象中所有的旧值
// replaceAll 使用新值替换 List 对象中所有的旧值 Collections.replaceAll(list, "a", "ab"); System.out.println(list);
同步控制
Collections 类中提供了多个 svnchronizedXxx() 方法,该方法可将指定集合包装成线程同步的集合,从而可以解决多线程并发访问集合使的线程安全问题。