develog

Collection List<Map> sort 본문

Dev/Java

Collection List<Map> sort

냐옴 2013. 5. 16. 16:35

public class CollectionUtil {

    

    public static void sort(List<Map<String, Object>> list, String keyNm) {

        sort(list, keyNm, false);

    }

    

    public static void sort(List<Map<String, Object>> list, String keyNm, boolean descOrder) {

        Comparator<Map<String, Object>> comparator = new ListMapComparator(keyNm);

        Collections.sort(list, comparator);

        

        if (descOrder) {

            Collections.reverse(list);

        }

    }

    

}


class ListMapComparator implements Comparator<Map<String, Object>> {

    

    private String keyNm;

    

    public ListMapComparator(String keyNm) {

        this.keyNm = keyNm;

    }

    

    public int compare(Map<String, Object> map1, Map<String, Object> map2) {

        String value1 = String.valueOf(map1.get(keyNm));

        String value2 = String.valueOf(map2.get(keyNm));

        return value1.compareTo(value2);

    }

}


----------------------------------------------------------------------------------------


사용예)

List<Map<String, Object>> list = getList();

CollectionUtil.sort(list, "REG_TS");        // 오름차순

CollectionUtil.sort(list, "REG_TS", true); // 내림차순


'Dev > Java' 카테고리의 다른 글

Collection List<Map> sort  (0) 2013.05.16
Web scraper open source  (0) 2013.05.16
Java API for RESTful Web Services  (0) 2013.05.15
GET, POST 전송  (0) 2013.05.14
REST Tutorial  (0) 2013.05.13
Comments