RankSorter { public static <T> List<T> sort(Collection<T> items, int[] itemRanks) { Guard.argumentNotNull(items, "items"); Guard.argumentNotNull(itemRanks, "itemRanks"); int lastObserverdRank = 0; boolean needToSort = false; for (int currentRank : itemRanks) { if (currentRank < lastObserverdRank) { needToSort = true; break; } lastObserverdRank = currentRank; } if (!needToSort) return new ArrayList<T>(items); List<T> itemsInList = new ArrayList<T>(items); final Map<T, Integer> itemToRank = new HashMap<T, Integer>(); for (int i = 0; i < itemsInList.size(); i++) itemToRank.put(itemsInList.get(i), itemRanks[i]); Collections.sort(itemsInList, new Comparator<T>() { public int compare(T o1, T o2) { return itemToRank.get(o1).compareTo(itemToRank.get(o2)); } }); Arrays.sort(itemRanks); return itemsInList; }  static List<T> sort(Collection<T> items, int[] itemRanks);  }
@Test public void sortAlreadySortedTest() { List<String> people = Arrays.asList("One", "Two", "Three"); int[] ranks = {1, 2, 3}; int[] sortedRanks = {1, 2, 3}; people = RankSorter.sort(people, ranks); for (int i = 0; i < people.size(); i++) { assertEquals(String.format("Different at index %d. Expected <%d>, was <%d>.", i, sortedRanks[i], ranks[i]), ranks[i], sortedRanks[i]); } assertEquals(people, Arrays.asList("One", "Two", "Three")); }
@Test public void sortUnsortedTest() { List<String> people = Arrays.asList("Five", "Two1", "Two2", "One", "Four"); int[] ranks = {5, 2, 2, 1, 4}; int[] sortedRanks = {1, 2, 2, 4, 5}; people = RankSorter.sort(people, ranks); for (int i = 0; i < people.size(); i++) { assertEquals(String.format("Different at index %d. Expected <%d>, was <%d>.", i, sortedRanks[i], ranks[i]), ranks[i], sortedRanks[i]); } assertEquals(people, Arrays.asList("One", "Two1", "Two2", "Four", "Five")); }