JAVA

[Java] - Map - getOrDefault란?

nam_ji 2024. 10. 9. 18:19

getOrDefault 사용법 및 예제

getOrDefault란

  • Java 8에서 추가된 Collection API 함수들 중 일부입니다.
  • V getOrDefault(Object Key, Object defaultValue)
  • 찾는 Key가 존재한다면 찾는 key의 value를 반환하고 없거나 null이면 default 값을 반환합니다.

getOrDefault 사용법

getOrDefault(Object key, V DefaultValue)
  • key: map 요소의 키입니다.
  • defaultValue: 지정된 키로 매핑된 값이 없거나 null이면 반환하는 기본 값입니다.

getOrDefault 예제

  1. solutionOne -> key 값이 빈 값이면 0으로 초기화
  2. solutionTwo -> key 값이 빈 값이면 1으로 초기화
  3. solutionThree -> key값이 빈 값이면 0으로 초기화 후 1 더하기
  4. solutionFour -> key값이 빈 값이면 0으로 초기화 동일한 key 값이 존재해도 0으로 초기화
  5. solutionFive -> key값이 빈 값이면 0으로 초기화 후 1 더하기 동일한 key 값이 존재해도 0으로 초기화 후 1 더하기
package 자료구조;

import java.util.HashMap;

public class GetOrDefault {
  public static void main(String[] args) {
    String[] str = {"a", "b", "c", "d"};

    solutionOne(str);
    solutionTwo(str);
    solutionThree(str);
    solutionFour();
    solutionFive();

  }
  public static void solutionOne(String[] str) {
    HashMap<String, Integer> mapOne = new HashMap<>();

    for (String key: str) {
      mapOne.put(key, mapOne.getOrDefault(key, 0));
    }
    System.out.println("\nkey값이 빈 값이면 0으로 초기화");
    System.out.println("key의 value 값이 빈 값이면 default 값 0 : " + mapOne);
  }
  public static void solutionTwo(String[] str) {
    HashMap<String, Integer> mapTwo = new HashMap<>();

    for (String key: str) {
      mapTwo.put(key, mapTwo.getOrDefault(key, 1));
    }
    System.out.println("\nkey값이 빈 값이면 1으로 초기화");
    System.out.println("key의 value 값이 빈 값이면 default 값 1 : " + mapTwo);
  }
  public static void solutionThree(String[] str) {
    HashMap<String, Integer> mapThree = new HashMap<>();

    for (String key: str) {
      mapThree.put(key, mapThree.getOrDefault(key, 0) + 1);
    }
    System.out.println("\nkey값이 빈 값이면 0으로 초기화 후 1 더하기");
    System.out.println("key의 value 값이 빈 값이면 default 값 1 : " + mapThree);
  }
  public static void solutionFour() {
    HashMap<String, Integer> mapFour = new HashMap<>();
    String[] str = {"a", "b", "c", "d", "d"};

    for (String key: str) {
      mapFour.put(key, mapFour.getOrDefault(key, 0));
    }
    System.out.println("\nkey값이 빈 값이면 0으로 초기화 동일한 key 값이 존재해도 0으로 초기화");
    System.out.println("key의 value 값이 빈 값이면 default 값 1 : " + mapFour);
  }
  public static void solutionFive() {
    HashMap<String, Integer> mapFive = new HashMap<>();
    String[] str = {"a", "b", "c", "d", "d"};

    for (String key: str) {
      mapFive.put(key, mapFive.getOrDefault(key, 0) + 1);
    }
    System.out.println("\nkey값이 빈 값이면 0으로 초기화 후 1 더하기 동일한 key 값이 존재해도 0으로 초기화 후 1 더하기");
    System.out.println("key의 value 값이 빈 값이면 default 값 1 : " + mapFive);
  }
}