Java Collection.sort 排序升序, 降序问题

2022-10-25,,,,

不多说,记住2点, 直接上代码(下面是降序):

package mall;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; public class TestSort2 {
public static void main(String[] args) {
List<Test> list = new ArrayList<Test>(); String [] n = {"a", "b", "c", "d", "e", "f", "g" , "h" , "i", "j", "k"};
double [] d = {0, 0, 34581, 0, 22017, 20807, 0 , 0 , 20443.2, 44457,0};
double [] a = {400, 0, 400, 200, 150, 400, 600, 300, 200, 500, 0};
for (int i = 0; i < a.length; i++) {
Test s = new Test(n[i], d[i], a[i]);
list.add(s);
} //假如A的值大于B,你返回1 ,这样调用Collections.sort()方法就是升序
//假如A的值大于B,你返回-1,这样调用Collections.sort()方法就是降序
Collections.sort(list, new Comparator<Test>() {
//总销售额(大->小)
public int compare(Test o1, Test o2) {
if(o1.getTotalPrice().compareTo(o2.getTotalPrice()) == 1)
return -1;
return 0;
}
}); for (int i = 0; i < list.size(); i++) {
Test s = list.get(i);
System.out.println("价格:"+s.getTotalPrice() + " , 面积:" + s.getArea());
}
} static class Test {
private String name;
private Double totalPrice;
private Double area; public Test(String name, double totalPrice, double area){
this.name = name;
this.totalPrice = totalPrice;
this.area = area;
} public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Double totalPrice) {
this.totalPrice = totalPrice;
}
public Double getArea() {
return area;
}
public void setArea(Double area) {
this.area = area;
} }
}

Java Collection.sort 排序升序, 降序问题的相关教程结束。

《Java Collection.sort 排序升序, 降序问题.doc》

下载本文的Word格式文档,以方便收藏与打印。