java list排序的两种方式

用Collections.sort方法对list排序有两种方法

第一种方法是根据Collections.sort重载方法来实现,如下:

package com.gaopeng.springboot.listcompare;

public class User1 {
    private String name;
    private Integer order;
    private Integer price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getOrder() {
        return order;
    }

    public void setOrder(Integer order) {
        this.order = order;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

}

 

package com.gaopeng.springboot.listcompare;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Test1 {

    public static void main(String[] args) {
        User1 user1 = new User1();
        user1.setName("a");
        user1.setPrice(11);
        
        User1 user2 = new User1();
        user2.setName("b");
        user2.setPrice(2);

        Set<User1> Hset = new HashSet<User1>();
        Hset.add(user2);
        Hset.add(user1);

        List<User1> list = new ArrayList<User1>();
        list.addAll(Hset);

        Collections.sort(list, new Comparator<User1>() {
            public int compare(User1 arg0, User1 arg1) {
                return arg0.getPrice().compareTo(arg1.getPrice());
            }
        });
        
        for (User1 u : list) {
            System.out.println(u.getName());
        }
    }

}

 

第二种是list中的对象实现Comparable接口,如下:

package com.gaopeng.springboot.listcompare;

/**
 * 根据order对User排序
 */
public class User2 implements Comparable<User2> {
    private String name;
    private Integer order;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getOrder() {
        return order;
    }

    public void setOrder(Integer order) {
        this.order = order;
    }

    public int compareTo(User2 arg0) {
        return this.getOrder().compareTo(arg0.getOrder());
    }
}

 

package com.gaopeng.springboot.listcompare;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test2 {

    public static void main(String[] args) {
        User2 user1 = new User2();
        user1.setName("a");
        user1.setOrder(1);
        
        User2 user2 = new User2();
        user2.setName("b");
        user2.setOrder(2);
        
        List<User2> list = new ArrayList<User2>();
        
        // 此处add user2再add user1
        list.add(user2);
        list.add(user1);
        Collections.sort(list);
        for (User2 u : list) {
            System.out.println(u.getName());
        }
    }

}

 

posted @ 2019-12-06 14:06  gaopengpy  阅读(721)  评论(0编辑  收藏  举报