HashMap의 getOrDefault()와 putIfAbsent() 차이점

728x90

⬛ 1) map.getOrDefault(key, defaultValue)

  • 기존 map에 해당 key가 존재 O → 해당 key의 value를 반환
  • 기존 map에 해당 key가 존재 X → 설정해둔 defaultValue를 반환

사용 예시


String[] a = {"steve", "hulk", "thor", "steve"};

HashMap<String, Integer> map = new HashMap<>();
for(String x : a) {
    map.put(x, map.getOrDefault(x, 0)+1); //중복없이 누적
}

⬛ 2) map.putIfAbsent(key, value)

  • 기존 map에 해당 key가 존재 O → 그냥 건너뛴다.
  • 기존 map에 해당 key가 존재 X → 해당 키에 설정한 value값을 넣는다.

사용 예시

HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("A", 1);
        map.put("B", 1);
        map.put("C", 1);
        map.put("D", null);

        System.out.println("result : " + map.toString());
        //result : {A=1, B=1, C=1, D=null}

        map.putIfAbsent("E", 1);
        System.out.println("result1 : " + map);
        //result1 : {A=1, B=1, C=1, D=null, E=1}

        map.putIfAbsent("E", 2); //이미 값이 존재했기때문에 건너뜀
        System.out.println("result2 : " + map);
        //result2 : {A=1, B=1, C=1, D=null, E=1}

        map.putIfAbsent("D", 1);
        System.out.println("result3 : " + map);
        //result3 : {A=1, B=1, C=1, D=1, E=1}

728x90