简体   繁体   中英

Sorting objects inside arraylist

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?

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.

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM