「Java入門」Mapのリストをソートするサンプル

Javaコード:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ListSortDemo {

public static void main(String[] args) {

List<Map<Object, Object>> lst = new ArrayList<Map<Object, Object>>();

Map<Object, Object> mapAA = new HashMap<Object, Object>();
Map<Object, Object> mapBB = new HashMap<Object, Object>();
Map<Object, Object> mapCC = new HashMap<Object, Object>(); ·

mapAA.put(“number”, “4”);
mapBB.put(“number”, “4.15”);
mapCC.put(“number”, “5.67”);
lst.add(mapAA);
lst.add(mapBB);
lst.add(mapCC);

Collections.sort(lst, new Comparator<Map<Object, Object>>() {

public int compare(Map<Object, Object> o1, Map<Object, Object> o2) {

int mapAAVal = (int)Double.parseDouble((String) o1.get(“number”))*100 ;
int mapBBVal = (int)Double.parseDouble((String) o2.get(“number”))*100;
return mapAAVal – mapBBVal;
}
});
System.out.println(lst);
}
}

Comments are closed.