Let me explain the scenario first:
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]
I want to sort elements of column1
in ascending order and elements of column2
in descending order. Like:
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]
I am not sure whether this can achieve this by using:
Collections.sort(rowValues); //or
Collections.sort(rowValues, Collections.reverseOrder());
Row class, if that makes any sense:
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();
}
}