当前位置:网站首页>List. How to achieve ascending and descending sort() 2020.8.6

List. How to achieve ascending and descending sort() 2020.8.6

2022-07-07 23:28:00 codepig16

The following code is directed to a list Add three numbers to the set , Then in ascending order 、 Descending order , Print .
Be careful :o1 Represents the next number ,o2 Represents the previous number ,-1 Represents the swap position ,1 Indicates no exchange

@Test
    public void test() {
    
        List<Integer> list = new ArrayList<>();
        list.add(3);
        list.add(1);
        list.add(2);
        print_list(list);

        // Descending order 
        list.sort(new Comparator<Integer>() {
    
            @Override
            public int compare(Integer o1, Integer o2) {
    
                //o1  Represents the next number  o2 Represents the previous number 
                if (o1 > o2)return -1; //-1 Indicates the position of exchanging two numbers   So here is a descending order 
                else return 1;
            }
        });
        print_list(list);
        
        // Ascending order 
        list.sort(new Comparator<Integer>() {
    
            @Override
            public int compare(Integer o1, Integer o2) {
    
                if (o1 < o2) return -1; //-1 Represents the position of exchanging two numbers 
                else return 1;
            }
        });
        print_list(list);
    }

    public void print_list(List<Integer> list) {
    
        for (Integer i : list) {
    
            System.out.print(i);
            System.out.print(" ");
        }
        System.out.println();
    }


The printing result is shown in the figure below :

 Insert picture description here

原网站

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