ぶろぐ

日記です

BeanのソートはCommons BeanUtils使えば一行でいける


http://d.hatena.ne.jp/ariteku/20120523/p1
に関連。

ということはあれだ

BeanComparatorを使えば

// List<HogeBean> beans = Hoge.findAll();
Collections.sort(beans, new BeanComparator("key"));

の一発でいけるわけだ。
使わない場合は

// List<HogeBean> beans = Hoge.findAll();
Collections.sort(beans, new Comparator<HogeBean>() {
	@Override
	public int compare(HogeBean o1, HogeBean o2) {
		int comp = compareString(o1.getKey(), o2.geKey());
		if (comp != 0) {
			return comp;
		}
		return 0;
	}
});

private int compareString(String s1, String s2) {
	if (s1 == null && s2 == null) {
		return 0;
	} else if (s1 == null) {
		return -1;
	} else if (s2 == null) {
		return 1;
	} else {
		return s1.compareTo(s2);
	}
}

これかな…。
だいぶ楽だぞ!Commons BeanUtils!