IdComparator implements Comparator<AbstractEntity<Integer>> { @Override public int compare(AbstractEntity<Integer> o1, AbstractEntity<Integer> o2) { if (o1.getId() == null) { return -1; } if (o2.getId() == null) { return 1; } return o1.getId().compareTo(o2.getId()); }  @Override int compare(AbstractEntity<Integer> o1, AbstractEntity<Integer> o2);  }
@Test public void test() { TestEntity t1 = new TestEntity("name", 12L); t1.setId(4); TestEntity t2 = new TestEntity("name", 12L); t2.setId(3); TestEntity t3 = new TestEntity("name", 12L); t3.setId(null); assertEquals(0, new IdComparator().compare(t1, t1)); assertEquals(1, new IdComparator().compare(t1, t2)); assertEquals(-1, new IdComparator().compare(t2, t1)); assertEquals(-1, new IdComparator().compare(t3, t1)); assertEquals(1, new IdComparator().compare(t1, t3)); }