按照对象中自定义的值优先级对JAVA 11中的对象列表进行排序。

huangapple go评论64阅读模式
英文:

Sort a list of Object according to custom priority of value in the Object JAVA 11

问题

我有一个 **Student(name, result, rollNo)** 对象的列表

    List.of(
                    new Student("Sam", "Pass", "100"),
                    new Student("Gill", "Not available", "101"),
                    new Student("Joe", "Fail", "111"),
                    new Student("Matt", "Fail", "115"),
                    new Student("Ann", "Pass", "121"),
                    new Student("Moss", "Pass", "133")
            );

我需要根据以下要求对上述列表进行排序我使用的是 Java 11):
1. 按照学生的 **result** 进行排序顺序为 "Fail""Pass""Not available"不是按字母顺序排列
   结果为 "Fail" 的学生应排在列表顶部然后是 "Pass"最后是 "Not available"
2. 如果有多名学生的结果相同则按 **rollNo** 的升序排序

最终结果应如下所示

    {"Joe", "Fail", "111"}
    {"Matt", "Fail", "115"}
    {"Sam", "Pass", "100"}
    {"Ann", "Pass", "121"}
    {"Moss", "Pass", "133"}
    {"Gill", "Not available", "101"}
英文:

I have a list of Student(name, result, rollNo) objects.

List.of(
                new Student("Sam", "Pass", "100"),
                new Student("Gill", "Not available", "101"),
                new Student("Joe", "Fail", "111"),
                new Student("Matt", "Fail", "115"),
                new Student("Ann", "Pass", "121"),
                new Student("Moss", "Pass", "133"),
        );

I need to sort the above list as per the below requirements(I am using Java 11)

  1. Sort the list in the order of the result of students in the order "Fail", "Pass", "Not available"(Not in alphabetical order)
    Students with results fail should come at the top of the list. Then "pass" and then "Not available"
  2. If multiple students have the same result, then sort in the ascending order of rollNo.

The end result should be as shown below.

{"Joe", "Fail", "111"}
{"Matt", "Fail", "115"}
{"Sam", "Pass", "100"}
{"Ann", "Pass", "121"}
{"Moss", "Pass", "133"}
{"Gill", "Not available", "101"}

答案1

得分: 5

自从Java 8以来,我们可以对多个字段进行流排序

当您想要按优先级排序为 "Fail"、"Pass"、"Not available" 时,一种替代方法是在学生中添加一个额外的字段。这将有助于在没有自然顺序时决定排序的优先级。在这个示例中,学生按照 "Pass"、"Fail"、"Not available" 的顺序排序,然后按照姓名排序,以展示一些更多的选项。

排序代码片段:

Comparator<Student> compareByPriorityThenName =
        Comparator.comparing(Student::getPriority)
                .thenComparing(Student::getName);

List<Student> sortedStudents = students.stream()
        .sorted(compareByPriorityThenName)
        .collect(Collectors.toList());

上下文中的代码片段:

public static void main(String []args){

    List<Student> students = List.of(
            new Student("Sam", "Pass", "100"),
            new Student("Gill", "Not available", "101"),
            new Student("Joe", "Fail", "111"),
            new Student("Matt", "Fail", "115"),
            new Student("Ann", "Pass", "121"),
            new Student("Moss", "Pass", "133")
    );

    Comparator<Student> compareByPriorityThenName =
            Comparator.comparing(Student::getPriority)
                    .thenComparing(Student::getName);

    List<Student> sortedStudents = students.stream()
            .sorted(compareByPriorityThenName)
            .collect(Collectors.toList());

    sortedStudents.forEach(System.out::println);
}

输出:

Student{name='Ann', result='Pass', rollNo='121', priority='1'}
Student{name='Moss', result='Pass', rollNo='133', priority='1'}
Student{name='Sam', result='Pass', rollNo='100', priority='1'}
Student{name='Joe', result='Fail', rollNo='111', priority='2'}
Student{name='Matt', result='Fail', rollNo='115', priority='2'}
Student{name='Gill', result='Not available', rollNo='101', priority='3'}

在Student类中添加的字段:

private int priority;

在Student类中添加的用于按优先级排序的方法:

public int getPriority() {
    setPriority();
    return priority;
}

private int setPriority() {
    if(priority > 0) {
        return priority;
    }

    switch(result) {
    case "Pass":
        priority = 1;
        break;
    case "Fail":
        priority = 2;
        break;
    default:
        priority = 3;
    }
    return priority;
}

上下文中的getPriority()方法:

public class Student {

    private final String name;
    private final String result;
    private final String rollNo;
    private int priority;

    public Student(String name, String result, String rollNo) {
        this.name = name;
        this.result = result;
        this.rollNo = rollNo;
        this.priority = 0;
    }

    public String getName() {
        return name;
    }

    public String getResult() {
        return result;
    }

    public String getRollNo() {
        return rollNo;
    }

    public int getPriority() {
        setPriority();
        return priority;
    }

    private int setPriority() {
        if(priority > 0) {
            return priority;
        }

        switch(result) {
        case "Pass":
            priority = 1;
            break;
        case "Fail":
            priority = 2;
            break;
        default:
            priority = 3;
        }
        return priority;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", result='" + result + '\'' +
                ", rollNo='" + rollNo + '\'' +
                ", priority='" + priority + '\'' +
                '}';
    }
}
英文:

Since Java 8 we can do Sorting stream on multiple fields

When you want to sort by priority "Fail", "Pass", "Not available", one alternative is to add an extra field in students. This will help to decide the priority of the sorting when there is no natural order. In this example student are ordered by "Pass", "Fail", "Not available" and then sorted by name, just to show some more options.

Sorting code snippet:

    Comparator&lt;Student&gt; compareByPriorityThenName =
Comparator.comparing(Student::getPriority)
.thenComparing(Student::getName);
List&lt;Student&gt; sortedStudents = students.stream()
.sorted(compareByPriorityThenName)
.collect(Collectors.toList());

Code Snippet in context:

public static void main(String []args){
List&lt;Student&gt; students = List.of(
new Student(&quot;Sam&quot;, &quot;Pass&quot;, &quot;100&quot;),
new Student(&quot;Gill&quot;, &quot;Not available&quot;, &quot;101&quot;),
new Student(&quot;Joe&quot;, &quot;Fail&quot;, &quot;111&quot;),
new Student(&quot;Matt&quot;, &quot;Fail&quot;, &quot;115&quot;),
new Student(&quot;Ann&quot;, &quot;Pass&quot;, &quot;121&quot;),
new Student(&quot;Moss&quot;, &quot;Pass&quot;, &quot;133&quot;)
);
Comparator&lt;Student&gt; compareByPriorityThenName =
Comparator.comparing(Student::getPriority)
.thenComparing(Student::getName);
List&lt;Student&gt; sortedStudents = students.stream()
.sorted(compareByPriorityThenName)
.collect(Collectors.toList());
sortedStudents.forEach(System.out::println);
}

Output:

Student{name=&#39;Ann&#39;, result=&#39;Pass&#39;, rollNo=&#39;121&#39;, priority=&#39;1&#39;}
Student{name=&#39;Moss&#39;, result=&#39;Pass&#39;, rollNo=&#39;133&#39;, priority=&#39;1&#39;}
Student{name=&#39;Sam&#39;, result=&#39;Pass&#39;, rollNo=&#39;100&#39;, priority=&#39;1&#39;}
Student{name=&#39;Joe&#39;, result=&#39;Fail&#39;, rollNo=&#39;111&#39;, priority=&#39;2&#39;}
Student{name=&#39;Matt&#39;, result=&#39;Fail&#39;, rollNo=&#39;115&#39;, priority=&#39;2&#39;}
Student{name=&#39;Gill&#39;, result=&#39;Not available&#39;, rollNo=&#39;101&#39;, priority=&#39;3&#39;}

Added field in Student:

private int priority;

Added methods for sorting priority in class Student:

public int getPriority() {
setPriority();
return priority;
}
private int setPriority() {
if(priority &gt; 0) {
return priority;
}
switch(result) {
case &quot;Pass&quot;:
priority = 1;
break;
case &quot;Fail&quot;:
priority = 2;
break;
default:
priority = 3;
}
return priority;
}

Method getPriority() in context:

public class Student {
private final String name;
private final String result;
private final String rollNo;
private int priority;
public Student(String name, String result, String rollNo) {
this.name = name;
this.result = result;
this.rollNo = rollNo;
this.priority = 0;
}
public String getName() {
return name;
}
public String getResult() {
return result;
}
public String getRollNo() {
return rollNo;
}
public int getPriority() {
setPriority();
return priority;
}
private int setPriority() {
if(priority &gt; 0) {
return priority;
}
switch(result) {
case &quot;Pass&quot;:
priority = 1;
break;
case &quot;Fail&quot;:
priority = 2;
break;
default:
priority = 3;
}
return priority;
}
@Override
public String toString() {
return &quot;Student{&quot; +
&quot;name=&#39;&quot; + name + &#39;\&#39;&#39; +
&quot;, result=&#39;&quot; + result + &#39;\&#39;&#39; +
&quot;, rollNo=&#39;&quot; + rollNo + &#39;\&#39;&#39; +
&quot;, priority=&#39;&quot; + priority + &#39;\&#39;&#39; +
&#39;}&#39;;
}
}

huangapple
  • 本文由 发表于 2020年8月27日 12:33:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63609245.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定