Java学习笔记——操作集合的工具类:Collections

操作集合的工具类: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处元素进行交换

package day10;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Test7 {
	public static void main(String[] args) {
		List<String> list=new ArrayList<String>();
		list.add("b");
		list.add("cd");
		list.add("ac");
		list.add("a");
		list.add("21");
		list.add("3");
		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, 4);//将指定list集合小红放入i处元素和j处元素进行交换
		System.out.println(list);
		
		Student s1=new Student(14,"张三");
		Student s2=new Student(12,"李四");
		Student s3=new Student(25,"王五");
		Student s4=new Student(34,"赵六");
		List<Student> stus=new ArrayList<Student>();
		stus.add(s1);
		stus.add(s2);
		stus.add(s3);
		stus.add(s4);
		
		for(Student stu:stus){
			System.out.println(stu.name+","+stu.age);
		}
		
		//根据指定的Comparator产生的顺序对List集合元素排序
		Collections.sort(stus, new Student());
		System.out.println("===根据指定的Comparator产生的顺序对List集合元素排序====");
		for(Student stu:stus){
			System.out.println(stu.name+","+stu.age);
		}
		
	}
}

class Student implements Comparator<Student>{
	int age;
	String name;
	public Student(){
		
	}

	public Student(int age, String name) {
		super();
		this.age = age;
		this.name = name;
	}


	@Override
	public int compare(Student o1, Student o2) {//根据年龄升序排列对象
		if(o1.age>o2.age){
			return 1;
		}else if(o1.age<o2.age){
			return -1;
		}else{
			return 0;
		}
		
	}
	
}

Object max(Collection):根据元素中的自然顺序,返回给定集合中的最大元素
Object max(Collecyion,Comparator):根据Comparator指定的顺序,返回给定集合中的最大元素
Object min(Collection)
Object min(Collecyion,Comparator)
int frequency(Collection,Object):返回指定集合中指定元素的出现次数
boolean replaceAll(List list,Object oldVal,Object newVal):使用新值替换List对象的所有旧值

		System.out.println(Collections.max(list));
		System.out.println(Collections.min(list));

		Student s=Collections.max(stus, new Student());
		System.out.println(s.name+","+s.age);
		Student ss=Collections.min(stus, new Student());
		System.out.println(ss.name+","+ss.age);

		System.out.println(Collections.frequency(list, "a"));
		
		Collections.replaceAll(list, "a", "aa");
		System.out.println(list);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值