オレオレクラスで、Collection.sortする。Comparator作ってね。
idが大きい順でソートしてみる
オレオレクラス
public class Hoge { private Long id; private String name; // getter とか setterとか略 }
オレオレComparator
class HogeComparator implements Comparator<Hoge> { @Override public int compare(Hoge o1, Hoge o2) { if (o1.getId() < o2.getId()) { return 1; } else if (o1.getId().equals(o2.getId())) { return 0; } else { return -1; } } }
クライアントのコード
public class fugafuga { public List<Hoge> sortHoge(List<Hoge> hoges) { Collections.sort(hoges, new HogeComparator()); return hoges }
テストコード
@Test public void sortTest1() { List<Hoge> input = new ArrayList<>(); List<Long> inputIds = Arrays.asList(1L,2L,3L); for (Long id : inputIds) { Hoge hoge = new Hoge(); hoge.setId(id); input.add(hoge); } List<Hoge> actual = new ArrayList<>(); List<Long> actualIds = Arrays.asList(3L,2L,1L); for (Long id : actualIds) { Hoge hoge = new Hoge(); hoge.setId(id); actual.add(hoge); } List<Hoge> expect = fugafuga.sortHoge(input); for (int i = 0; i < actual.size(); i++) { assertThat(actual.get(i).getId(), is(expect.get(i).getId())); } }