Java - HashMap 활용하기

JunMyung Lee·2021년 6월 11일
0

자바

목록 보기
1/7

computeIfAbsentputIfAbsent

둘다 인자로 입력받은 key값을 가지고 처리한다.
단, putIfAbsent는 키의 개수만큼 실행이되는 반면, computeIfAbsent는 키의값이 없는 경우에만 수행된다.

Map<String, String> temp2 = new HashMap<>(){{
     put("test1","test1");
     put("test2","test2");
     put("test3","test3");
  }};

  //computeIfAbsent
  List<String> list = List.of("test1", "test2","test3","test4");
  for(String str : list){
      temp2.computeIfAbsent(str, (key) ->  print(key));
  }
  System.out.println("---------------------------");
  // putIfAbsent
  for(String str : list){
      temp2.putIfAbsent(str, print(str));
  }
  /*
      [result]
      test4
      ---------------------------
      test1
      test2
      test3
      test4
   */

computeIfPresentcompute

Map을 이용하여 빈도 계산시에 추천
내부의 값으로 연산할때 필요함, compute의 경우 없는 키값이면 예외발생

String text = "KOREA KOREA USA USA USA CANADA JAPAN ";
        Map<String, Integer> wordMap = new HashMap<>();
        wordMap.put("KOREA", 0);
        wordMap.put("USA", 0);
        wordMap.put("CHINA", 0);
        wordMap.put("JAPAN", 0);

        //computeIfPresent
        for(String word : text.split(" ")){
            wordMap.computeIfPresent(word, (String key, Integer value) -> ++value);
        }
        System.out.println("wordMap = " + wordMap);

        //compute
        for(String word : text.split(" ")){
            wordMap.compute(word, (String key, Integer value) -> ++value);
        }
        System.out.println("wordMap = " + wordMap);

        /*
            [Result]
            wordMap = {USA=3, CHINA=0, JAPAN=1, KOREA=2}
            Exception in thread "main" java.lang.NullPointerException
                at DateTest.lambda$main$1(DateTest.java:42)
                at java.base/java.util.HashMap.compute(HashMap.java:1228)
                at DateTest.main(DateTest.java:42)
         */

0개의 댓글