0

I am struggling sorting an array in order of an object's property. I know how to sort numbers in order, but I can't figure out how to do it with an object. For example, let's say object A has a position attribute of 1 and object B has a position attribute of 2. These objects are in an array. How could I sort them according to this property?

Thanks

foobar5512
  • 2,470
  • 5
  • 36
  • 52

2 Answers2

1

You have something like:

public class ExampleObject {
    public int position;
}

Then, simply use a Comparator.

public static void main(String args[]) {
    //example numbers
    final Random r = new Random();
    final List<ExampleObject> arrList = new ArrayList<>(100);
    for (int i = 0; i < 100; i++) {
        ExampleObject obj = new ExampleObject();
        obj.position = r.nextInt(1000);
        arrList.add(obj);
    }

    //comparator (as a lambda)
    Collections.sort(arrList, (a, b) -> {
        return a.position - b.position;
    });

    //output result
    for (ExampleObject obj : arrList) {
        System.out.println(obj.position);
    }
}

Also, in case you must sort an array and not a List, you can use Arrays.sort() with a Comparator like this as well.

Ken Slade
  • 343
  • 2
  • 8
0

You can compare by implementing Comparable interface in your class like below.

public class Applcation {
    public static void main(String[] args) {
        A ary[] = {new A("D", 1),new A("C", 7),new A("K", 4),new A("L", 8),new A("S", 3)};
        Arrays.sort(ary);
        for (A a : ary) {
            System.out.println(a.id+" - "+a.name);
        }
    }

}
class A implements Comparable<A>{

    String name;
    int id;

    public A(String name, int id) {
        this.name = name;
        this.id = id;
    }

    @Override
    public int compareTo(A a) {
        return this.id-a.id;
    }


}

Or as an alternative you can use java 8 streams to sort your array without implementing Comparable :

Arrays.stream(ary).sorted((a1,a2)->Integer.compare(a1.id, a2.id)).forEach(e->System.out.println(e.id+" - "+e.name));

Out-put :

1 - D
3 - S
4 - K
7 - C
8 - L         
Madushan Perera
  • 2,568
  • 2
  • 17
  • 36