【发布时间】:2021-05-26 00:51:38
【问题描述】:
我正在尝试使用 Guava Table 和 TreeBaedTable 实现,并且正在尝试按列名对表进行排序。这是我目前所拥有的:
import com.google.common.collect.Ordering;
import com.google.common.collect.Table;
import com.google.common.collect.TreeBasedTable;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class CustomTable {
enum SortDirection {
ASC, DESC,
}
enum Column {
COL_1, COL_2, COL_3;
public static final Column[] columns = Column.values();
}
private final TreeBasedTable<Integer, Column, Integer> table;
public CustomTable() {
this.table = TreeBasedTable.create();
}
public Integer cell(int ID, Column column) {
return table.get(ID, column);
}
public void addRow(List<Integer> values) {
Integer rowNum = nextID();
for (int i = 0; i < values.size(); i++) {
table.put(rowNum, Column.columns[i], values.get(i));
}
}
public Table<Integer, Column, Integer> sortBy(Column column, SortDirection sortDirection) {
Comparator<Integer> rowComparator = Comparator.comparing(id -> cell(id, column));
rowComparator = (sortDirection.equals(SortDirection.ASC)) ? rowComparator : rowComparator.reversed();
Table<Integer, Column, Integer> table = TreeBasedTable.create(rowComparator, Ordering.natural());
table.putAll(table);
return table;
}
public String toString() {
return table.toString();
}
public int maxID() {
return table.rowKeySet().size();
}
public int nextID() {
return maxID() + 1;
}
}
以及示例用法:
CustomTable table = new CustomTable();
table.addRow(Arrays.asList(1, 2, 3));
table.addRow(Arrays.asList(6, 7, 8));
table.addRow(Arrays.asList(4, 5, 6));
System.out.println(table.sortBy(Column.COL_2, SortDirection.DESC));
现在,当单元格具有不同的值时,这可以正常工作。但是,如果两个单元格的值相同,则省略后者。
我已尝试使用以下比较器解决此问题:
Comparator<Integer> rowComparator = (id1, id2) -> {
Integer cell1 = cell(id1, column);
Integer cell2 = cell(id2, column);
if (cell1 != cell2)
return cell1.compareTo(cell2);
return -1; // So, row id1 appears above the row id2.
};
但这会产生一些不需要的表格突变。我有什么遗漏吗?
【问题讨论】:
-
什么你想按列排序?单个细胞?
-
(为什么你不能只维护一个
Table<Column, Integer, Integer>呢?如果需要的话,你可以在它们之间转换,使用Tables.transpose。) -
@LouisWasserman 我正在尝试按列对整个行进行排序,而不仅仅是给定列中的单个单元格。此外,对我来说,转置表格会有什么不同并不是很明显。如果有帮助的话,这是一个排名系统。
-
@LouisWasserman 经过考虑,我已经尝试了您的解决方案,但仍然没有区别:当两个值相同时,排序仍然失败。
-
您不能以这种方式根据表格自身的值对表格进行排序。您将需要创建一个新的
Table或使用例如ImmutableTable保留插入顺序。
标签: java sorting guava comparator