应用Collection实现集合排序
package com.imooc.collection.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ListSorter {
class SampleComparator implements Comparator<Integer>{
//70 90 30 50
//结果>0,则交换位置
//结果=0或小于0,则位置不变
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;//o1-o2:升序;o2-o1:降序
}
}
public List<Integer> sort(List<Integer> list){
Collections.sort(list,new SampleComparator());//升序排列
System.out.println(list);
return list;
}
public static void main(String[] args) {
List<Integer> list=new ArrayList<>();
list.add(70);
list.add(90);
list.add(30);
list.add(50);
System.out.println(list);
ListSorter listSorter=new ListSorter();
List<Integer> list1=listSorter.sort(list);
System.out.println(list1);
}
}
-
自定义类型如何集合排序
package com.imooc.collection; public class Goods { private String sn; private String title; public Goods(String sn,String title){ this.title=title; this.sn=sn; } @Override public String toString(){ return "Goods{"+"sn='"+sn+'\''+",title='"+title+'\''+'}'; } public String getSn(){ return sn; } public String getTitle(){ return title; } }
package com.imooc.collection; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class CustomObjectSortSample { private class CustomComparator implements Comparator<Goods>{ @Override public int compare(Goods o1, Goods o2) { // return o1.getSn().compareTo(o2.getSn()); return o1.getTitle().compareTo(o2.getTitle()); } } public List<Goods> sort(List<Goods> list){ CustomComparator comp=new CustomComparator(); Collections.sort(list,comp); return list; } public static void main(String[] args) { List<Goods> goodsList=new ArrayList<>(); goodsList.add(new Goods("18827382190","商品A")); goodsList.add(new Goods("83219078978","商品B")); goodsList.add(new Goods("83241781237","商品C")); goodsList.add(new Goods("18579831426","商品D")); System.out.println("排序前"); System.out.println(goodsList); System.out.println("排序后"); List<Goods> list=new CustomObjectSortSample().sort(goodsList); System.out.println(list); } }