Java(자바)/Java 기본

Java List Map 객체 정렬하기

마샤와 곰 2022. 9. 5. 23:13

 

너무 쉬운 기능, Comparator를 얼마나 이해하고 잘 쓰냐에 따라 달려있습니다.

스트림(stream)으로 풀면 아래와 같습니다.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

public class SortItem {

    public static void main(String[] args) {

        List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> item = new HashMap<>();
        item.put("index", 1);
        item.put("text", "abcd");
        list.add(item);

        item = new HashMap<>();
        item.put("index", 5);
        item.put("text", "efg");
        list.add(item);

        item = new HashMap<>();
        item.put("index", 2);
        item.put("text", "hij");
        list.add(item);
        
        //#1 스트림 활용한 정렬 방법
        Comparator<HashMap<String, Object>> todo = Comparator.comparing( 
            (HashMap<String,Object> arg)-> {
                return Integer.parseInt(arg.get("index").toString());
            }
        );   

        list.stream().sorted(todo).forEach(System.out::println);
    }

}

 

아니면 Collections.sort 메소드를 사용해도 가능합니다.

자바스크립트(Javascript)에서 배열을 정렬하는 sort 함수를 사용한 사람이라면 아래가 더 쉽다고 느낄 거 같습니다.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class SortItem {

    public static void main(String[] args) {

        List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> item = new HashMap<>();
        item.put("index", 1);
        item.put("text", "abcd");
        list.add(item);

        item = new HashMap<>();
        item.put("index", 5);
        item.put("text", "efg");
        list.add(item);

        item = new HashMap<>();
        item.put("index", 2);
        item.put("text", "hij");
        list.add(item);
        
        //#1 스트림 활용한 정렬 방법
        //Comparator<HashMap<String, Object>> todo = Comparator.comparing( 
        //    (HashMap<String,Object> arg)-> {
        //        return Integer.parseInt(arg.get("index").toString());
        //    }
        //);  

        //#2 Collections의 sort 메서드를 활용한 방법
        Collections.sort(list, (v1, v2)-> {
            int a = Integer.parseInt(v1.get("index").toString());
            int b = Integer.parseInt(v2.get("index").toString());
            return a - b;
        });
        list.stream().forEach(System.out::println);
        
    }

}

 

틀린점 또는 궁금한점은 언제든 연락주세요! 👻

끝!

반응형