简体   繁体   English

Java List对对象字段的常量值进行排序

[英]Java List sort on object fields constant values

I have a enum representing severity level 我有一个代表严重程度的枚举

public enum Severity {
    HIGH("H"), MEDIUM("M"), LOW("L");
}

Person one = new Person();
one.setSeverity(Severity.HIGH);

other fields ... 其他领域...

Person two = new Person();
two.setSeverity(Severity.LOW);

..... .....

Person three = new Person();
three.setSeverity(Severity.HIGH);

List<Person> persons = Lists.newArrayList();
persons.add(one);
persons.add(two);
persons.add(three);

I would like to sort persons list to sort by severity field (ie HIGH,MEDIUM then LOW). 我想对人员列表进行排序,以按严重性字段(即HIGH,MEDIUM然后LOW)进行排序。

My expected results after sorting the persons list should be in the order of HIGH,HIGH,LOW ? 对人员列表进行排序后,我的预期结果应为HIGH,HIGH,LOW?

can i know how i can achieve this ? 我能知道我如何做到这一点吗?

note : I am making use of com.google.common.collect 注意:我正在使用com.google.common.collect

Try below code 试试下面的代码

Create an ENUM 创建一个ENUM

package com.rais;

public enum Severity {
    HIGH("H"), MEDIUM("M"), LOW("L");

    private final String  value;

    private Severity(String value) {
        this.value = value;
    }



}

Now Create Person class according to your requirement eg. 现在根据您的要求创建Person类。

package com.rais;

public class Person {

    private Severity severity;
    private String name;


    public Person(Severity severity, String name) {
        super();
        this.severity = severity;
        this.name = name;
    }

    public Severity getSeverity() {
        return severity;
    }

    public void setSeverity(Severity severity) {
        this.severity = severity;
    }

    public String getName() {
        return name;
    }

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

}

Finally create a Test Client and apply below logic. 最后,创建一个测试客户端并应用以下逻辑。

package com.rais;

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

public class TestClient {

    public static void main(String[] args) {

        Person one = new Person(Severity.HIGH, "shayam");
        Person two = new Person(Severity.MEDIUM, "mohan");
        Person three = new Person(Severity.LOW, "radha");
        Person four = new Person(Severity.HIGH, "rakesh");
        Person five = new Person(Severity.MEDIUM, "kailash");
        Person six = new Person(Severity.LOW, "rais");
        Person seven = new Person(Severity.LOW, "abhishek");

        List<Person> persons = new ArrayList<Person>();
        persons.add(one);
        persons.add(two);
        persons.add(three);
        persons.add(four);
        persons.add(five);
        persons.add(six);
        persons.add(seven);

        Collections.sort(persons, new Comparator<Person>() {

            @Override
            public int compare(Person person1, Person person2) {

                if(person1.getSeverity()==person2.getSeverity())
                {
                    return person1.getName().compareTo(person2.getName());
                }
                else{
                    return person1.getSeverity().compareTo(person2.getSeverity());
                }

            }
        });

        for (Person person : persons) {
            System.out.println(person.getName()+" "+ person.getSeverity());

        }

    }

}

I am sure you will get below output. 我相信你会得到下面的输出。

rakesh HIGH
shayam HIGH
kailash MEDIUM
mohan MEDIUM
abhishek LOW
radha LOW
rais LOW

Use Comparable or comparator and then apply Collection.sort() . 使用Comparable或比较器,然后应用Collection.sort()

if using comparable interface you have to implement compareTo method and 如果使用类似的接口,则必须实现compareTo方法和

Collection.sort(<list>)

and if using comparator then you have to override compareTo method and 如果使用比较器,则必须重写compareTo方法和

Collection.sort(<list>, <comparator>)

and when to use comparatot or comparable read link: 以及何时使用比较或类似的阅读链接:

http://iandjava.blogspot.in/2012/10/comparable-and-comparator.html http://iandjava.blogspot.in/2012/10/comparable-and-comparator.html

If you are using Google Collections, upgrade to Google Guava. 如果您使用的是Google Collections,请升级到Google Guava。 Use its ComparisonChain class. 使用其CompareChain类。 Are you sure you want HIGH , MEDIUM , LOW in that order? 您确定要MEDIUM顺序选择HIGHMEDIUMLOW吗? The reverse fits Java comparisons better. 反向比较适合Java比较。

How do Person s have a severity level? Person的严重程度如何? Perhaps your class deserves a better name. 也许您的班级应该有一个更好的名字。

I would make Person implement Comparable , which makes the sorting code very simple and brief. 我将使Person实现Comparable ,这使排序代码非常简单和简短。

Note that enums are implicitly Comparable: 请注意,枚举是隐式可比较的:

public enum Severity {
    HIGH("H"), MEDIUM("M"), LOW("L");

    private final String code;

    private Severity(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}

public class Person implements Comparable<Person> {

    private Severity severity;
    private final String name;

    public Person(Severity severity, String name) {
        this.severity = severity;
        this.name = name;
    }

    public Severity getSeverity() {
        return severity;
    }

    public void setSeverity(Severity severity) {
        this.severity = severity;
    }

    public String getName() {
        return name;
    }

    @Override
    public int compareTo(Person person) {
        return severity == person.severity ? name.compareTo(person.name)
                : severity.compareTo(person.severity);
    }

    @Override
    public String toString() {
        return name + "(" + severity +")";
    }
}

Now some test code: 现在一些测试代码:

Person one = new Person(Severity.HIGH, "one");
Person two = new Person(Severity.LOW, "two");
Person three = new Person(Severity.HIGH, "three");

List<Person> persons = new ArrayList<Person>();
persons.add(one);
persons.add(two);
persons.add(three);

Collections.sort(persons);

System.out.println(persons);

Output: 输出:

[one(HIGH), three(HIGH), two(LOW)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM