javacodex.com
Java Examples
Java Examples
memu home questions

How to sort array of objects by a property value?

Implement a Comparator as follows:

Collections.sort(list, new Comparator() {
   public int compare(Thing t1, Thing t2) {
     return Integer.valueOf(t1.getNumber()).compareTo(t2.getNumber());
   }
});

Thing.java

public class Thing {
 
    private String name;
    private int number;
 
    public Thing(String name, int number) {
        this.name = name;
        this.number = number;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getNumber() {
        return number;
    }
 
    public void setNumber(int number) {
        this.number = number;
    }
}
 

Program.java

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
 
public class Program {
 
    public static void main(String[] args) {
 
        ArrayList<Thing> list = new ArrayList();
        list.add(new Thing("AA", 2));
        list.add(new Thing("BB", 1));
        list.add(new Thing("CC", 3));
 
        Collections.sort(list, new Comparator<Thing>() {
            public int compare(Thing t1, Thing t2) {
                return Integer.valueOf(t1.getNumber()).compareTo(t2.getNumber());
            }
        });
 
        for(Thing thing: list){
            System.out.println(thing.getName() + " " + thing.getNumber());
        }
 
    }
}
 

Output

$ java Program
BB 1
AA 2
CC 3

Questions answered by this page:

How to sort array of objects by a property value? Sort an Array of Objects by Property Sort ArrayList of custom Objects by property Sort Array Of Objects Based On A Specified Property How do I sort an array of objects with a Comparator?




Contact: javacodex@yahoo.com