1

For instance:

class A{
    public int a;
    public String b;

    public A(int a, String b){
        this.a = a;
        this.b = b;
    }
}


main(){
    List<A> list = new Arraylist<>();
    list.add(new A(5, "abc"));
    list.add(new A(1, "aee"));
    list.add(new A(3, "adf"));
    list.add(new A(6, "aad"));
    list.add(new A(2, "xx"));
}

Is there any way to sort this list in ascending order using the integer in A class. I've already tried

Collection.sort(list) but getting some syntax error. What I'm doing wrong.

jpm
  • 1,042
  • 2
  • 12
  • 36

4 Answers4

1

You need a custom Comparator implementation:

Collections.sort(list, new Comparator<A>() {
    public int compare(A first, A second) {
        return Integer.compare(first.a, second.a);
    }
});
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
1

Using Java8 List.sort and a lambda expression for the Comparator you can write:

list.sort((a1,a2) -> a1.a - a2.a);
wero
  • 32,544
  • 3
  • 59
  • 84
0

Use custom Comparator

Collections.sort(list, new Comparator<A>() {

                @Override
                public int compare(A o1, A o2) {

                if(o1.a==o2.a){
                    return 0;
                }else {
                   return o1.a>o2.a?1:-1;
                }
              }

            });
Rustam
  • 6,485
  • 1
  • 25
  • 25
0
    List<A> listElements = new ArrayList<>();
    listElements.add(new A(5, "abc"));
    listElements.add(new A(1, "aee"));
    listElements.add(new A(3, "adf"));
    listElements.add(new A(6, "aad"));
    listElements.add(new A(2, "xx"));
    //Sorting
    Collections.sort(listElements, new Comparator<Pourtest.A>() {
        @Override
        public int compare(A o1, A o2) {
            return Integer.compare(o1.a, o2.a);
        }
    });
    //Verify
    for (A listElement : listElements) {
        System.out.println(listElement.a);
    }
Aroniaina
  • 1,252
  • 13
  • 31
  • Your comparator doesn't isn't anti-symmetrical: it should return 0 for o1.a == o2.a. Integer.compare(o1.a, o2.a) is easier. – Andy Turner Oct 08 '15 at 08:28