How to sort an ArrayList?

后端 未结 20 2133
有刺的猬
有刺的猬 2020-11-22 06:19

I have a List of doubles in java and I want to sort ArrayList in descending order.

Input ArrayList is as below:

List testList = new Arr         


        
20条回答
  •  遥遥无期
    2020-11-22 06:43

    For example I have a class Person: String name, int age ==>Constructor new Person(name,age)

    import java.util.Collections;
    import java.util.ArrayList;
    import java.util.Arrays;
    
    
    public void main(String[] args){
        Person ibrahima=new Person("Timera",40);
        Person toto=new Person("Toto",35);
        Person alex=new Person("Alex",50);
        ArrayList myList=new ArrayList
        Collections.sort(myList, new Comparator() {
            @Override
            public int compare(Person p1, Person p2) {
                // return p1.age+"".compareTo(p2.age+""); //sort by age
                return p1.name.compareTo(p2.name); // if you want to short by name
            }
        });
        System.out.println(myList.toString());
        //[Person [name=Alex, age=50], Person [name=Timera, age=40], Person [name=Toto, age=35]]
        Collections.reverse(myList);
        System.out.println(myList.toString());
        //[Person [name=Toto, age=35], Person [name=Timera, age=40], Person [name=Alex, age=50]]
    
    }
    

提交回复
热议问题