KeywordSort { public static Comparator<KeywordBean> searchResultsSorter(final String searchTerm, final SortDirection direction) { final Comparator<KeywordBean> defaultSorter = defaultLabelSorter(direction); final String normSearchTerm = normalizeDesc(searchTerm); return new Comparator<KeywordBean>() { public int compare(final KeywordBean kw1, final KeywordBean kw2) { String defValue1 = normalizeDesc(kw1.getDefaultValue()); String defValue2 = normalizeDesc(kw2.getDefaultValue()); int sim1 = calcSim(defValue1, normSearchTerm); int sim2 = calcSim(defValue2, normSearchTerm); if (sim1 != sim2) { sim1 = sim1 * (6 - Math.min(5, defValue1.length() - normSearchTerm.length())); sim2 = sim2 * (6 - Math.min(5, defValue2.length() - normSearchTerm.length())); return sim2 - sim1; } return defaultSorter.compare(kw1, kw2); } @Override public String toString() { return "Prioritize: " + normSearchTerm + ", other order: " + direction; } }; } private  KeywordSort(); static Comparator<KeywordBean> defaultLabelSorter(final SortDirection direction); static Comparator<KeywordBean> defaultDefinitionSorter(final SortDirection direction); static Comparator<KeywordBean> searchResultsSorter(final String searchTerm, final SortDirection direction); static String normalizeDesc(String rawDesc);  }
@Test public void testSearchResultsSorter() throws Exception { Comparator<KeywordBean> comparator = KeywordSort.searchResultsSorter("wate", SortDirection.DESC); KeywordBean waterBean = new KeywordBean(new IsoLanguagesMapper()).setValue("Water", "eng").setDefaultLang("eng"); KeywordBean waterSurfaceBean = new KeywordBean(new IsoLanguagesMapper()).setValue("Water (Surface)", "eng").setDefaultLang("eng"); KeywordBean waterAgricultureBean = new KeywordBean(new IsoLanguagesMapper()).setValue("Water Agriculture", "eng").setDefaultLang("eng"); KeywordBean waterGeogBean = new KeywordBean(new IsoLanguagesMapper()).setValue("Water (Geographic)", "eng").setDefaultLang("eng"); KeywordBean wasteWaterBean = new KeywordBean(new IsoLanguagesMapper()).setValue("Waste Water", "eng").setDefaultLang("eng"); KeywordBean wasteWaterTreatmentBean = new KeywordBean(new IsoLanguagesMapper()).setValue("Waste Water treatment", "eng").setDefaultLang("eng"); KeywordBean atmosphereWaterBean = new KeywordBean(new IsoLanguagesMapper()).setValue("Atmosphere Water", "eng").setDefaultLang("eng"); ArrayList<KeywordBean> expected = Lists.newArrayList(waterBean, waterAgricultureBean, waterGeogBean, waterSurfaceBean, atmosphereWaterBean, wasteWaterBean, wasteWaterTreatmentBean); Collection<List<KeywordBean>> permutations = Collections2.permutations(expected); for (List<KeywordBean> permutation : permutations) { ArrayList<KeywordBean> copy = Lists.newArrayList(permutation); Collections.sort(copy, comparator); assertArrayEquals(expected.toArray(), copy.toArray()); } }