让我先解释一下情景:排序值按特定的顺序
List<Row> rowValues = new ArrayList<>();
// After adding values into list
At location 0 = [Johnson, 10000]
At location 1 = [Adam, 12000]
At location 2 = [Mike, 11000]
At location 3 = [Johnson, 17000]
At location 4 = [Tony, 10000]
我想升序和降序排列的column1
元素column2
元素进行排序。像:
At location 0 = [Adam, 12000]
At location 1 = [Johnson, 17000]
At location 2 = [Johnson, 10000]
At location 3 = [Mike, 11000]
At location 4 = [Tony, 10000]
我不知道这是否能实现这一目标,通过使用:
Collections.sort(rowValues); //or
Collections.sort(rowValues, Collections.reverseOrder());
Row类,如果让任何意义:
final class Row extends ArrayList<Object> implements Comparable<Row> {
private int index;
private Order order;
Row(int initialCapacity) {
super(initialCapacity);
this.index = -1; //-1 indicates that the index has not been set
}
Object getSortingValue() {
if (index == -1) {
throw new IllegalStateException("Sorting column is unknown");
} else if (isEmpty()) {
throw new IllegalStateException("Row is empty");
}
return get(index);
}
void setSortingColumn(int index) throws IllegalArgumentException {
if (index < 0) {
throw new IllegalArgumentException("Invalid sorting index: " + index);
}
this.index = index;
}
Order getOrder() {
return order;
}
void setOrder(Order order) {
this.order = order;
}
@Override
public int compareTo(Row row) {
if (row == null) {
throw new NullPointerException();
}
Object sortValue = getSortingValue();
if (sortValue instanceof Comparable) {
return ((Comparable) sortValue).compareTo(row.getSortingValue());
} else {
throw new IllegalArgumentException(sortValue + " not type of Comparable");
}
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Row) {
Row row = (Row) obj;
return getSortingValue().equals(row.getSortingValue());
}
return false;
}
@Override
public int hashCode() {
return getSortingValue().hashCode();
}
}
创建自己的类,它实现'比较'。你可以让它定义你想要的订单。 –
rgettman
@Lucky_Singh如果你用你的Row类编辑你的文章,我可以用代码更新我的答案,以达到你想要的。 –
@ HugoSousa增加了Row类。 –