java 操作集合的工具类Collections

上次总结了一下集合的相关内容,这次总结一下,集合的操作类Collection类。

Collections简介如下:

Collections的一些常用操作:

具体代码中的应用如下:

public class Test8 {

    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("ada");
        list.add("bb");
        list.add("cc");
        list.add("dd");
        list.add("ee");
        System.out.println(list);
        Collections.reverse(list);//反转list集合
        System.out.println(list);
        Collections.shuffle(list);//对list集合进行随机排序
        System.out.println(list);
        Collections.sort(list);//对List集合进行字典升序排列
        System.out.println(list);
        Collections.swap(list, 0, 1);//交换指定位置元素
        System.out.println(list);
        System.out.println(Collections.max(list));//返回最大值
        System.out.println(Collections.frequency(list,"ada"));//返回指定元素出现次数
        Collections.replaceAll(list, "cc", "bb");//替换元素
        
        
        
        
        
        
        Student s1 = new Student("张三",13);
        Student s2 = new Student("赵四",19);
        Student s3 = new Student("王五",17);
        Student s4 = new Student("孙六",16);
        Student s5 = new Student("吴七",23);
        
        List<Student> stu = new ArrayList<Student>();
        stu.add(s1);
        stu.add(s2);
        stu.add(s3);
        stu.add(s4);
        stu.add(s5);
        for(Student st:stu) {
            System.out.println(st.name+"    "+st.age);
        }
        
        System.out.println("==============================");
        Collections.sort(stu,new Student());//通过年龄从小到大排序
        for(Student st:stu) {
            System.out.println(st.name+"    "+st.age);
        }
        
        Student s = Collections.max(stu, new Student());
        System.out.println(s.name+"    "+s.age);
        
        
    }
}

class Student implements Comparator<Student>{//通过年龄从小到大排序

    int age;
    String name;
    public Student() {
        
    }
    
    public Student(String name,int age) {
        this.age = age;
        this.name = name;
    }
    @Override
    public int compare(Student arg0, Student arg1) {
        if(arg0.age > arg1.age) {
            return 1;
        }else if(arg0.age < arg1.age) {
            return -1;
        }
        else {
            return 0;
        }
        
    }
    
}
Collections操作集合基本应用
原文地址:https://www.cnblogs.com/wfswf/p/14637297.html