I need to sort a list of strings that I'm reading in but the sorted order of that list is not predetermined (I can't hard code it); I read in the sort order from a source and build a comparator by assigning a numerical value to each entry in a map and then use that to determine the order.
My implementation is pretty simple and straightforward. I don't know if there is any room to optimize this but given that sorting is generally a slow process in itself, I wanted to submit this for code review in case there are in fact any improvements to be made.
The custom comparator will be cached after creation so I won't be building a new one unless required to do so.
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class RunTest {
// Runnable test
public static void main(String[] args) {
CustomComparator comparator = CustomComparator.fromList(getSortOrder());
List<String> list1 = getTestList();
System.out.println("Test list: \n " + list1);
Collections.sort(list1, comparator);
System.out.println("Test list (sorted): \n " + list1);
}
// Comparator
public static class CustomComparator implements Comparator<String> {
private Map<String, Integer> _sortOrder;
public CustomComparator(Map<String, Integer> sortOrder) {
_sortOrder = sortOrder;
}
@Override
public int compare(String l, String r) {
Integer lvalue = _sortOrder.get(l);
Integer rvalue = _sortOrder.get(r);
if (lvalue == null || rvalue == null)
return 0;
if (lvalue < rvalue)
return -1;
return 1;
}
public static CustomComparator fromList(List<String> sortOrder) {
// Map each list item to a comparable integer
Map<String, Integer> customSortOrder = new HashMap<>();
int i = 0;
for (String s : sortOrder)
customSortOrder.put(s, i++);
return new CustomComparator(customSortOrder);
}
}
// Custom sort order
public static List<String> getSortOrder() {
List<String> customSortOrder = new LinkedList<>();
customSortOrder.add("c");
customSortOrder.add("b");
customSortOrder.add("a");
return customSortOrder;
}
// Test list
public static List<String> getTestList() {
List<String> randomList = new LinkedList<>();
randomList.add("b");
randomList.add("a");
randomList.add("c");
return randomList;
}
}
Output:
Test list: [b, a, c] Test list (sorted): [c, b, a]