[英]Sorting objects inside arraylist
I have an ArrayList of some class type, in particular: 我有一些类类型的ArrayList,特别是:
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? 是否可以对row和col的myList从升序进行排序? 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? 是否可以对列表进行排序,而不是在
**RowColElem**
类中实现Comparable
或Comparator
?
Yes you can achieve this using Comparator
methods. 是的,您可以使用
Comparator
方法来实现。 It is fairly neat in Java 8: 在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. Comparator
接口具有一些非常有用的静态和默认方法-值得一看。
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. 如果要在插入新元素时使集合保持排序,则可能要考虑使用
TreeSet
或其他自排序结构而不是ArrayList
具体取决于您的用例。 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. 否则,您可能必须实现自己的
SortedList
类,该类可以透明地进行插入排序。
Either way, you'll have to implement Comparable<RowColElem<T>>
on your class. 无论哪种方式,您都必须在类上实现
Comparable<RowColElem<T>>
。 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. 您将必须实现Comparable接口,并且您的类RowColElement必须提供compareTo方法的实现,如果您不想实现这些接口,则必须扩展ArrayList并必须提供自己的实现。 This is not a good idea, the best way will be to implement the interfaces and provide the custom comparison logic
这不是一个好主意,最好的方法是实现接口并提供自定义比较逻辑
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.