操作集合的工具类:Collections
- Collections是一个操作Set、List和Map等集合的工具类
- Collections中提供了大量方法对集合元素进行排序、查询和修改等操作,还提供了对集合对象设置不可变、对集合对象实现同步控制等方法
- 排序操作
- reverse(List):反转List中元素的顺序
- shuffle(List):对List集合元素进行随机排序.
- sort(List):根据元素的自然顺序对指定List集合元素按升序排序
- sort(List,Comparator):根据指定的Comparator产生的顺序对List集合元素进行排序
- swap(List,Int,Int):将指定List集合中的I处元素和J处元素进行交换
- Object max(Collection):根据元素的自然顺序,返回给定集合中的最大元素
- Object max(Collection,Comparator):根据Comparator指定的顺序,返回给定集合中的最大元素
- Object min(Collection)
- Object min(Collection,Comparator)
- int frequency(Collection,Object):返回指定集合中指定元素的出现次数
- boolean replaceAll(List list,Object oldVal,Object newVal):使用新值替换 List对象的所有旧值
public class CollectionsDemo {
public static void main(String[] args) {
List<String> list= new ArrayList<>();
list.add("你好");
list.add("rt");
list.add("csgo");
list.add("ak47");
list.add("rt");
System.out.println(list);//[你好, rt, csgo, ak47, rt]
//返回指定集合中指定元素的出现次数
System.out.println(Collections.frequency(list,"rt"));//2
//反转List中元素的顺序
Collections.reverse(list);
System.out.println(list);//[rt, ak47, csgo, rt, 你好]
//对List集合元素进行随机排序
Collections.shuffle(list);
System.out.println(list);//[rt, csgo, 你好, ak47, rt]
//根据元素的自然顺序对指定List集合元素按升序排序
Collections.sort(list);
System.out.println(list);//[ak47, csgo, rt, rt, 你好]
//根据元素的自然顺序,返回给定集合中的最大元素/最小值
System.out.println(Collections.max(list));//你好
System.out.println(Collections.min(list));//ak47
//:使用新值替换 List对象的所有旧值
// oldVal - 要替换的旧值。
//newVal - 要替换 oldVal的新值。
Collections.replaceAll(list,"rt","hzc");
System.out.println(list);//[ak47, csgo, hzc, hzc, 你好]
//根据指定的Comparator产生的顺序对List集合元素进行排序;
Student p1=new Student(22,"张三");
Student p2=new Student(20,"李四");
Student p3=new Student(26,"王五");
Student p4=new Student(24,"Hello");
List<Student> list1 = new ArrayList<Student>();
list1.add(p1);
list1.add(p2);
list1.add(p3);
list1.add(p4);
//根据Comparator指定的顺序,返回给定集合中的最大元素
Student s = Collections.max(list1,new Student());
System.out.println(s.name + " " + s.age);//王五 26
//根据Comparator指定的顺序,返回给定集合中的最小元素
Student min = Collections.min(list1,new Student());
System.out.println(min.name + " " + min.age);//李四 20
for (Student x:list1) {
System.out.println(x.name + " " + x.age);
//张三 22
//李四 20
//王五 26
//Hello 24
}
System.out.println("================");
Collections.sort(list1,new Student());
for (Student x:list1) {
System.out.println(x.name + " " + x.age);
//李四 20
//张三 22
//Hello 24
//王五 26
}
//将指定List集合中的I处元素和J处元素进行交换 I和J是索引下标
Collections.swap(list,2,3);
System.out.println(list);//[ak47, csgo, rt, rt, 你好]
}
}
class Student implements Comparator<Student> {
int age;
String name;
public Student(){
}
public Student(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public int compare(Student o, Student o1) {//年龄正序排列
if (o.age > o1.age) {
return 1;
}else if (o.age < o1.age) {
return -1;
}else {
return 0;
}
}
}
同步控制
Collections类中提供了多个svnchronizedXxx()方法,该方法可使将指定集合包装成线程同步的集合,从而可以解决多线程并发访问集合时的线程安全问题