list排序方法一Comparator形式:
1.比较数字
1List<Shoes> all_shoes = new ArrayList<Shoes>(); 2Collections.sort(all_shoes, new Comparator<Shoes>(){ 3 @Override 4 /* * 5 * int compare(String o1, String o2) 返回一个基本类型的整型 6 * 返回-1表示:shoes1.getSimilarity()大于等于shoes2.getSimilarity(), 7 * 返回1表示:shoes1.getSimilarity()小于shoes2.getSimilarity(), 8 * */ 9 public int compare(Shoes shoes1, Shoes shoes2) { 10 if (shoes1.getSimilarity()<shoes2.getSimilarity()){ 11 return 1; 12 }else{ 13 return -1; 14 } 15 } 16}); 17System.out.println("比较后"); 18for(Shoes s:all_shoes) { 19 System.out.println(s.getId()); 20 System.out.println(s.getShoes_name()); 21 System.out.println(s.getPrice()); 22 System.out.println(s.getDeal()); 23 System.out.println(s.getImage()); 24 System.out.println(s.getShop_name()); 25 System.out.println(s.getAddress()); 26 System.out.println(s.getUrl()); 27 System.out.println(s.getSource()); 28 System.out.println(s.getSimilarity()); 29 System.out.println("--------------------------"); 30}
运行结果(similarity按从大到小顺序排列):




2.字符串型
1package dao; 2 3import java.util.ArrayList; 4import java.util.Collections; 5import java.util.Comparator; 6import java.util.List; 7 8/** 9*@author chenmeiqi 10*@version 2020年2月24日 下午12:13:17 11*/ 12public class test1 { 13 14 public static void main(String[] args) { 15 // TODO Auto-generated method stub 16 List<String> keyList = new ArrayList<>(); 17 keyList.add("abc"); 18 keyList.add("fgh"); 19 keyList.add("cvb"); 20 System.out.println("排序前:"); 21 for(String s:keyList) { 22 System.out.println(s); 23 } 24 25 Collections.sort(keyList, new Comparator<String>(){ 26 @Override 27 public int compare(String o1, String o2) { 28 /* 29 * * int compare(String o1, String o2) 返回一个基本类型的整型, 30 * * 返回负数表示:o1 小于o2, 31 * * 返回0 表示:o1和o2相等, 32 * * 返回正数表示:o1大于o2 33 * */ 34 if (o1.compareTo(o2) > 0){ 35 return 1; 36 }else if (o1.compareTo(o2) > 0){ 37 return 0; 38 }else{ 39 return -1; 40 } 41 } 42 }); 43 System.out.println("排序后:"); 44 for(String s:keyList) { 45 System.out.println(s); 46 } 47 48 } 49 50}
运行结果:
