list排序方法一Comparator形式:
1.比较数字
List<Shoes> all_shoes = new ArrayList<Shoes>();
Collections.sort(all_shoes, new Comparator<Shoes>(){
@Override
/* *
* int compare(String o1, String o2) 返回一个基本类型的整型
* 返回-1表示:shoes1.getSimilarity()大于等于shoes2.getSimilarity(),
* 返回1表示:shoes1.getSimilarity()小于shoes2.getSimilarity(),
* */
public int compare(Shoes shoes1, Shoes shoes2) {
if (shoes1.getSimilarity()<shoes2.getSimilarity()){
return 1;
}else{
return -1;
}
}
});
System.out.println("比较后");
for(Shoes s:all_shoes) {
System.out.println(s.getId());
System.out.println(s.getShoes_name());
System.out.println(s.getPrice());
System.out.println(s.getDeal());
System.out.println(s.getImage());
System.out.println(s.getShop_name());
System.out.println(s.getAddress());
System.out.println(s.getUrl());
System.out.println(s.getSource());
System.out.println(s.getSimilarity());
System.out.println("--------------------------");
}
运行结果(similarity按从大到小顺序排列):
2.字符串型
package dao;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
*@author chenmeiqi
*@version 2020年2月24日 下午12:13:17
*/
public class test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> keyList = new ArrayList<>();
keyList.add("abc");
keyList.add("fgh");
keyList.add("cvb");
System.out.println("排序前:");
for(String s:keyList) {
System.out.println(s);
}
Collections.sort(keyList, new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
/*
* * int compare(String o1, String o2) 返回一个基本类型的整型,
* * 返回负数表示:o1 小于o2,
* * 返回0 表示:o1和o2相等,
* * 返回正数表示:o1大于o2
* */
if (o1.compareTo(o2) > 0){
return 1;
}else if (o1.compareTo(o2) > 0){
return 0;
}else{
return -1;
}
}
});
System.out.println("排序后:");
for(String s:keyList) {
System.out.println(s);
}
}
}
运行结果: