对list中对象按某属性排序

2021-03-11 11:39:06 浏览数 (1)

1.方式一:(推荐)

代码语言:javascript复制
SDict item = new SDict();
item.setParentId("0271f6d5ffbbf5a3a447e16274b7bfc8");
List children = item.getParent().getChildren();
//根据orderNum对list中的sdict对象排序
 children.sort(Comparator.comparing(SDict::getOrderNum));

实际上只要一句话children.sort(Comparator.comparing(SDict::getOrderNum));

1.方式一:(不推荐)

让该对象实体类实现Comparable接口重写compareTo方法

代码语言:javascript复制
public class TestA implements Comparable<TestA> {
    private String name;

    private Integer age;

    public TestA(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "TestA [name="   name   ", age="   age   "]";
    }

    @Override
    public int compareTo(TestA o) {
        return this.age.compareTo(o.getAge());
    }
    
}

然后在需要排序的地方,进行比较排序

代码语言:javascript复制
Collections.sort(list, new Comparator<TestA>() {
            @Override
            public int compare(TestA o1, TestA o2) {
                //升序
                return o1.getAge().compareTo(o2.getAge());
            }
        });

2.方式二:(不推荐)

让该对象实体类实现Comparable接口重写compareTo方法

代码语言:javascript复制
public class TestA implements Comparable<TestA> {
    private String name;

    private Integer age;

    public TestA(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "TestA [name="   name   ", age="   age   "]";
    }

    @Override
    public int compareTo(TestA o) {
        return this.age.compareTo(o.getAge());
    }
    
}

然后在需要排序的地方,进行比较排序

代码语言:javascript复制
Collections.sort(list, new Comparator<TestA>() {
            @Override
            public int compare(TestA o1, TestA o2) {
                //升序
                return o1.getAge().compareTo(o2.getAge());
            }
        });

3.对比两种方式

自用整理,原文https://www.cnblogs.com/wdzhz/p/11583359.html

0 人点赞