OrderedComparator implements Comparator<T>, Serializable { @Override public int compare(T o1, T o2) { return order ? o1.getOrder() - o2.getOrder() : o2.getOrder() - o1.getOrder(); } OrderedComparator();  OrderedComparator(boolean smallToLarge); @Override int compare(T o1, T o2);  }
@Test public void testCompare() throws Exception { List<Obj> list = new ArrayList<Obj>(); list.add(new Obj("a", 10)); list.add(new Obj("b", 2)); list.add(new Obj("c", 6)); list.add(new Obj("d", 6)); list.add(new Obj("e", 0)); list.add(new Obj("f", -1)); list.add(new Obj("g", 10)); Collections.sort(list, new OrderedComparator<Obj>()); StringBuilder sb = new StringBuilder(); for (Obj test : list) { sb.append(test.getName()); } Assert.assertEquals(sb.toString(), "febcdag"); Collections.sort(list, new OrderedComparator<Obj>(false)); sb = new StringBuilder(); for (Obj test : list) { sb.append(test.getName()); } Assert.assertEquals(sb.toString(), "agcdbef"); }