I have created a Vector object to store data in Table object as Vector<Table>. Vector<Table> contains components as below.
[Vector<Record> records, String tableName, String keyColumnName, int recordCount, int columnCount]
I need to sort tableName in above Vector to my own order and return Vector<Table> with sorted tableNames for other processes.
I have wrote method as below.
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;
}
But I have no idea about how to write Comparator to this. My own sort order is stored in .properties file. I can read it and get value. But I have no idea about how to compare it.
How could I do it?
Before clarification
You need to write a
ComparatorforTableobjects that delegates to thetableName‘s comparator:Note that this will consider
Tables that have the same name to be equal. This can mess things up if you put these tables in aHashMaporHashSet. To avoid this, you can detect this case and returnone.hashCode() - two.hashCode()if the table names are the same.Guava’s
ComparisonChainis a convenient way to write such multi-stage comparisons:After clarification
Okay, the question is to impose a predefined sorting order rather than sorting the
Tables by name. In that case, you need to make aComparatorthat is aware of the ordering defined in the.propertiesfile.One way to achieve this is to initialize a mapping of table names to sorting order indices, and refer that mapping during the comparison. Given the property value:
SORT_ORDER = SALES,SALE_PRODUCTS,EXPENSES,EXPENSES_ITEMSThe mapping should look like:
Here’s what the comparator would look like:
To populate
orderIndexfrom the property value, you need to:getProperty()as you mentionedSplitter, butString.splitor others will work too)HashMap<String, Integer>and anint index = 0indexand incrementindexNote the implicit assumption that none of the table names have a comma in it.