编写Java比较器

Bis*_*han 3 java sorting vector comparator

我创建了一个Vector对象,以将数据存储在Table对象中Vector<Table>Vector<Table>包含以下组件。

[Vector<Record> records, String tableName, String keyColumnName, int recordCount, int columnCount]
Run Code Online (Sandbox Code Playgroud)

我需要按照tableName我自己的顺序对Vector 进行排序,然后返回Vector<Table>sorted tableNames进行其他处理。

我写了如下方法。

private Vector<Table> orderTables(Vector<Table> loadTables) {

    List<String> tableNames = new ArrayList<String>();

    for (Table table : loadTables) {

        String tblName = table.getTableName();
        tableNames.add(tblName);

    }
    Collections.sort(tableNames, new MyComparable());

    return null;
}
Run Code Online (Sandbox Code Playgroud)

但是我不知道该如何写Comparator。我自己的排序顺序存储在.properties文件中。我可以阅读并获得价值。但是我不知道如何比较。

我该怎么办?

oks*_*ayt 5

澄清之前

您需要编写一个Comparatorfor Table对象以委托给tableName比较器:

new Comparator<Table>() {
    @Override public int compare(Table one, Table two) {
        return one.getTableName().compareTo(two.getTableName());
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,这会将Table具有相同名称的视为相等。如果将这些表放在HashMap或中,可能会搞砸HashSet。为避免这种情况,您可以检测到这种情况并one.hashCode() - two.hashCode()在表名相同的情况下返回。

番石榴ComparisonChain是编写此类多阶段比较的便捷方法:

new Comparator<Table>() {
    @Override public int compare(Table one, Table two) {
        return ComparisonChain.start()
                 .compare(one.getTableName(), two.getTableName())
                 .compare(one.hashCode(), two.hashCode())
                 .result();
    }
}
Run Code Online (Sandbox Code Playgroud)

经过澄清

好的,问题是要施加预定义的排序顺序,而不是Table按名称对s进行排序。在这种情况下,您需要对文件中Comparator定义的顺序进行识别.properties

实现此目的的一种方法是初始化表名到排序顺序索引的映射,并在比较期间引用该映射。给定属性值:

SORT_ORDER = SALES,SALE_PRODUCTS,EXPENSES,EXPENSES_ITEMS

映射应如下所示:

{
    SALES: 0,
    SALE_PRODUCTS: 1,
    EXPENSES: 2,
    EXPENSES_ITEMS: 3
}
Run Code Online (Sandbox Code Playgroud)

这是比较器的外观:

private static class PredefinedOrderComparator implements Comparator<Table> {

    public PredefinedOrderComparator() {

        // Initialize orderIndex here

    }

    private final Map<String, Integer> orderIndex;

    @Override public int compare(Table one, Table two) {
        return orderIndex.get(one.getTableName()) - orderIndex.get(two.getTableName());
    } 

}
Run Code Online (Sandbox Code Playgroud)

要从orderIndex属性值填充,您需要:

  1. getProperty()如前所述,使用逗号分隔列表
  2. 用逗号分割该值(我建议使用Guava的Splitter,但String.split其他方法也可以使用)
  3. 初始化一个新的HashMap<String, Integer>和一个int index = 0
  4. 遍历拆分令牌,将当前令牌映射到index并递增index

请注意一个隐含的假设,即表名中都没有逗号。