Java/기본

[java] hashMap 순서를 유지하고 싶은 경우

vmpo 2021. 10. 4. 03:32

 

HashMap은 데이터의 순서가 보장되지 않는다.

아래 test1()을 실행해보면 출력결과가 입력한 순서대로 저장되지 않았다는 것을 알 수 있다.

 

HashMap의 순서를 보장하고 싶은경우에는 LinkedHashMap을 활용하면 된다.

public class MapTester {
  public static void main(String[] args) {
    test1();
    test2();
  }

  public static void test1(){
    System.out.println("HashMap->");
    Map<String,Integer> map = new HashMap<>();
    map.put("삼성전자",1);
    map.put("카카오",2);
    map.put("테스트",3);
    map.keySet().stream().forEach(System.out::println);
  }

  public static void test2(){
    System.out.println("LinkedHashMap->");
    Map<String,Integer> map = new LinkedHashMap<>();
    map.put("삼성전자",1);
    map.put("카카오",2);
    map.put("테스트",3);
    map.keySet().stream().forEach(System.out::println);
  }
}

#출력결과

HashMap->
카카오
테스트
삼성전자
LinkedHashMap->
삼성전자
카카오
테스트

 

LIST