0

I have an ArrayList of some class type, in particular:

ArrayList<RowColElem<T>> myList = new ArrayList<RowColElem<T>>();
myList.add(new RowColElem(4,4,11));
myList.add(new RowColElem(1,1,11));
myList.add(new RowColElem(3,3,11));
myList.add(new RowColElem(1,0,11));
myList.add(new RowColElem(3,0,11));

The output right now is:

[(4,4,11),(1,1,11),(3,3,11),(1,0,11),(3,0,11)]

Is it possible to sort myList from ascending order with regard to both row and col? So the output would be:

[(1,0,11),(1,1,11),(3,0,11),(3,3,11),(4,4,11)]

And is it possible to sort the list inside the class where it's located rather than implementing Comparable or Comparator in **RowColElem** class?

  • possible duplicate of [Sort ArrayList of custom Objects by property](http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) –  Sep 20 '15 at 09:59
  • @RC. not really. This question also asks how to sort by more than one criteria not just how to use custom properties. It's a fairly different question and it's not answered in the question you link. – sprinter Sep 20 '15 at 10:09
  • So there is an 'add' method in 'Arraylist' which expects three integers? Looks wrong, but what do I know... – Tom Sep 20 '15 at 10:11
  • @sprinter answer is the same, use a custom comparator. (NB: I upvoted you answer because it adds something) –  Sep 20 '15 at 11:21

3 Answers3

4

Yes you can achieve this using Comparator methods. It is fairly neat in Java 8:

Collections.sort(myList, 
    Comparator.comparingInt(RowColElem::getRow).thenComparingInt(RowColElem::getCol));

This will compare using the rows and then, if they are equal, the columns. The Comparator interface has some pretty useful static and default methods - it's worth taking a good look at it.

sprinter
  • 27,148
  • 6
  • 47
  • 78
1

If you want to keep your collection sorted as you insert new elements, you might want to consider using a TreeSet or another self-sorting structure instead of an ArrayList depending on your use case. These two structures will naturally keep themselves in sorted order when iterated over. Otherwise, you might have to implement your own SortedList class that does insertion sort transparently.

Either way, you'll have to implement Comparable<RowColElem<T>> on your class. It's fairly straight forward.

@Override
public int compareTo(RowColElem<T> o) {

    int rowComp = Integer.compare(this.row, o.row);

    if (rowComp == 0) {
        return Integer.compare(this.column, o.column);
    }

    return rowComp;
}
Ownaginatious
  • 787
  • 4
  • 14
1

You will have to implement the Comparable interface and your class RowColElement must provide the implementation of compareTo method, if you dont want to implement these interfaces you will have to extend ArrayList and will have to provide your own implementation. This is not a good idea, the best way will be to implement the interfaces and provide the custom comparison logic