集合排序的两种方法:自然排序和定制排序
实现集合的自定义排序
自然排序:如果集合里面的元素想进行自然排序,那么要求集合里面元素的引用类型必须实现Comparable接口,重写compareTo方法
定制排序:不按照自然排序的方式排序,使用自定义的方式进行排序,可以实现Comparator接口,重写compare方法(临时指定的方法)
普通方法:
/**
* 测试普通排序,通过Collection.sort(list)集合工具去测试
* 利用list.forEach(e->{})遍历
*/
@Test
public void m1(){
List<Integer> ls = new ArrayList<>();
ls.add(11);
ls.add(78);
ls.add(47);
ls.add(42);
ls.add(87);
//ls[0];
Collections.sort(ls);
System.out.println("排序后的列表:");
ls.forEach(e->{ System.out.print(" "+e); });
System.out.println();
//实现逆转
System.out.println("逆转后:");
Collections.reverse(ls);
ls.forEach(e->{ System.out.print(" "+e); });
//将列表转化成数组
// Object[] obs=ls.toString();
//List底层不是数组方式,所部不能利用[]
// Object obs=ls.toString();
// System.out.println(obs[0]);
}
自然排序:
@Test
public void m2(){
/**
* 通过创建学生对象测试集合中的自然排序和定制排序
*/
//自然排序
//自然排序:如果集合里面的元素想
// 进行自然排序,那么要求集合里面元素
// 的引用类型必须实现Comparable接口,重写compareTo方法
Student student1 = new Student("贾玲",30,"女");
Student student2 = new Student("马丽",40,"女");
Student student3 = new Student("Jack11111",28,"男");
Student student4 = new Student("沈腾",33,"男");
List<Student> students = new ArrayList<>();
students.add(student1);
students.add(student2);
students.add(student3);
students.add(student4);
System.out.println("排序前:");
students.forEach(e->{
System.out.println(e);
});
//通过年龄升序学生集合
System.out.println("排序后:");
Collections.sort(students);
students.forEach(e->{
System.out.println(e);
});
}
运行结果:
//测试定制方法:依据名字长度升序名字
@Test
public void m3(){
Student student1 = new Student("贾玲42",30,"女");
Student student2 = new Student("马丽32356",40,"女");
Student student3 = new Student("Jack11111",28,"男");
Student student4 = new Student("沈24腾",33,"男");
List<Student> students = new ArrayList<>();
students.add(student1);
students.add(student2);
students.add(student3);
students.add(student4);
/**
* 开始临时定制方法
*/
Collections.sort(students,(o1,o2)->{
return o1.getSname().length()-o2.getSname().length();
});
students.forEach(e-> System.out.println(e));
}
队列测试Queue
@Test
public void m4(){
Queue<String> queue = new LinkedList<>();
//入队列
queue.offer("mm");
queue.offer("bb");
queue.offer("nn");
queue.offer("yy");
//出队列
//返回弹出队列的元素
System.out.println("出栈的元素是:"+queue.poll());
queue.forEach(e->{
System.out.println(e);});
// queue.forEach(e->{ queue.remove(e);});//会报错
}
其中报错原因:不能边弹出边删除