2010/11/18 (Thu)
集合をソートしたい。 #2
java |
こう言うのって、どんなのが現実的な解なんでしょうね…。
上記を、我流で書き直すとしたら、毎度お馴染みguava-librariesを使って、こうですかね。
import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; public class Demo { public static void main(String[] args) { final List<String> yearMonths = ImmutableList.of( "2009-11", "2009-01", "2010-01", "2010-12", "2010-01", "2010-04", "2010-01", "2010-12", "2010-12", "2010-04"); //------(logic)-------------------- Map<String, Integer> countsSort = Maps.newTreeMap(Collections.reverseOrder()); Set<String> uniqueYearMonths = ImmutableSet.copyOf(yearMonths); for (String yearMonth : uniqueYearMonths) { Integer count = Iterables.frequency(yearMonths, yearMonth); countsSort.put(yearMonth, count); } System.out.println(countsSort); } }
上記記事を見ていたら、Scala版では、yearMonthsを再代入できない、不変のリストとして作っていたので、私もそれにならって。
Iterables#frequencyは、「集合の中に、その要素が何個あるかを数える」メソッドなので、そのまんま使ってます。
コメント
トラックバック - http://program.g.hatena.ne.jp/halflite/20101118