zoukankan      html  css  js  c++  java
  • Java Collection.sort 排序升序, 降序问题

    不多说,记住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;
            }
            
        }
    }
  • 相关阅读:
    bugKu getshell
    XCTF 进阶区 CAT
    php弱类型比较
    XCTF command_execution
    关于错误 openssl/ssl.h:没有那个文件或目录的解决办法
    libffi-dev : 依赖: libffi6 (= 3.2.1-4) 但是 3.2.1-4kord 正要被安装
    如何查看 Ubuntu下已安装包版本号
    git 下载指定tag版本的源码
    ubuntu 环境 openstack 源码包制成 deb 包
    fedora 国内源
  • 原文地址:https://www.cnblogs.com/eason-d/p/8118516.html
Copyright © 2011-2022 走看看