当前位置:网站首页>Case - grade sorting - TreeSet set storage

Case - grade sorting - TreeSet set storage

2022-06-13 05:05:00 Jason_ LH1024

package com.it03;

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

public class TreeSetDemo {
    public static void main(String[] args) {

        // establish TreeSet A collection of objects , Sort by comparator sort 
        // Anonymous inner class 
        Set<Student> set = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
//                return s2.getSum() - s1.getSum(); // Descending   From high to low   Main conditions 
                int num = s2.getSum() - s1.getSum();
                int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num;
                // The total score is the same, arranged by language 

                // Sort by first name   minor criteria 
                int num3 = num2 == 0 ? s1.getName().compareTo(s2.getName()) : num2;
                return num3;
            }
        });

        // Create student objects 
        Student s1 = new Student(" Liu ", 99, 99);
        Student s2 = new Student(" king ", 87, 89);
        Student s3 = new Student(" Zhang ", 89, 100);
        Student s4 = new Student(" Li ", 87, 87);

        Student s5 = new Student("la", 88, 88);
        Student s6 = new Student("hanhan", 88, 88);

        // Add student objects to the collection 
        set.add(s1);
        set.add(s2);
        set.add(s3);
        set.add(s4);
        set.add(s5);
        set.add(s6);

        // Ergodic set 
        for (Student s : set) {
            System.out.println(s.getName() + ",  Chinese language and literature :" + s.getChinese() + ", mathematics :" + s.getMath() + ", Total score :" + s.getSum());
        }


    }
}

use Comparator The comparator , Anonymous inner class

 

 

原网站

版权声明
本文为[Jason_ LH1024]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280515587951.html