ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JAVA] 맵 검색하기
    Java/Collection(컬렉션) 2024. 10. 4. 15:16
    반응형

    목차

       

      자바에서는 맵을 검색하는 다양한 방법이 있습니다. 이번 문서에서는 맵을 검색하는 여러 가지 방법에 대해 설명하겠습니다. 주요 메서드로는 키가 포함되어 있는지 검사, 값이 포함되어 있는지 검사, 특정 키에 연관된 값을 가져오는 방법, 특정 값에 연관된 키를 가져오는 방법, 특정 조건에 맞는 엔트리를 찾는 방법이 있습니다.

      1. 키가 포함되어 있는지 확인

      맵에 특정 키가 포함되어 있는지 확인할 때, containsKey 메서드를 사용합니다.
      /**
       * 주어진 맵에 특정 키가 포함되어 있는지 확인
       *
       * @param map 키가 포함되어 있는지 확인할 맵
       * @param key 확인할 키
       * @param <K> 키의 타입
       * @param <V> 값의 타입
       * @return 맵이 특정 키를 포함하고 있으면 {@code true}, 그렇지 않으면 {@code false}
       */
      public <K, V> boolean containsKey(Map<K, V> map, K key) {
        return map.containsKey(key);
      }
      단위 테스트
      @DisplayName("containsKey: 특정 키가 맵에 포함되어 있는지 확인")
      @Test
      void testContainsKey() {
      
        // given
        Map<String, Integer> map = Map.of("one", 1, "two", 2, "three", 3);
      
        // when
        boolean containsOne = mapSearch.containsKey(map, "one");
        boolean containsFour = mapSearch.containsKey(map, "four");
      
        // then
        assertAll(
            () -> assertTrue(containsOne),
            () -> assertFalse(containsFour)
        );
      }
       

       

      2. 값이 포함되어 있는지 확인

      맵에 특정 값이 포함되어 있는지 확인할 때, containsValue 메서드를 사용합니다.
      /**
       * 주어진 맵에 특정 값이 포함되어 있는지 확인
       *
       * @param map   값이 포함되어 있는지 확인할 맵
       * @param value 확인할 값
       * @param <K>   키의 타입
       * @param <V>   값의 타입
       * @return 맵이 특정 값을 포함하고 있으면 {@code true}, 그렇지 않으면 {@code false}
       */
      public <K, V> boolean containsValue(Map<K, V> map, V value) {
        return map.containsValue(value);
      }
      단위 테스트
      @DisplayName("containsValue: 특정 값이 맵에 포함되어 있는지 확인")
      @Test
      void testContainsValue() {
      
        // given
        Map<String, Integer> map = Map.of("one", 1, "two", 2, "three", 3);
      
        // when
        boolean containsValue2 = mapSearch.containsValue(map, 2);
        boolean containsValue5 = mapSearch.containsValue(map, 5);
      
        // then
        assertAll(
            () -> assertTrue(containsValue2),
            () -> assertFalse(containsValue5)
        );
      }

       

      3. 키와 연관된 값 조회

      주어진 키와 연관된 값을 조회할 때, get 메서드를 사용합니다.
      /**
       * 주어진 키와 연관된 값을 맵에서 조회
       *
       * @param map 값을 가져올 맵
       * @param key 해당 값과 연관된 키
       * @param <K> 키의 타입
       * @param <V> 값의 타입
       * @return 주어진 키와 연관된 값, 또는 키에 대한 매핑이 없으면 {@code null}
       */
      public <K, V> V getValueByKey(Map<K, V> map, K key) {
        return map.get(key);
      }
      단위 테스트
      @DisplayName("getValueByKey: 키를 사용하여 값을 조회")
      @Test
      void testGetValueByKey() {
      
        // given
        Map<String, Integer> map = Map.of("one", 1, "two", 2, "three", 3);
      
        // when
        int valueOne = mapSearch.getValueByKey(map, "one");
        Integer valueFour = mapSearch.getValueByKey(map, "four");
      
        // then
        assertAll(
            () -> assertEquals(1, valueOne),
            () -> assertNull(valueFour)
        );
      }

       

      4. 값과 연관된 키 조회

      주어진 값과 연관된 키를 조회할 때, getKey, getValue 메서드를 사용합니다.
      /**
       * 주어진 값과 연관된 키를 맵에서 조회
       *
       * @param map   키를 가져올 맵
       * @param value 해당 키와 연관된 값
       * @param <K>   키의 타입
       * @param <V>   값의 타입
       * @return 주어진 값과 연관된 키, 또는 값에 대한 매핑이 없으면 {@code null}
       */
      public <K, V> K getKeyByValue(Map<K, V> map, V value) {
        for (Map.Entry<K, V> entry : map.entrySet()) {
          if (entry.getValue().equals(value)) {
            return entry.getKey();
          }
        }
        return null;
      }
      단위 테스트
      @Order(4)
      @DisplayName("getKeyByValue: 값을 사용하여 키를 조회")
      @Test
      void testGetKeyByValue() {
      
        // given
        Map<String, Integer> map = new LinkedHashMap<>() {{
          put("one", 1);
          put("two", 2);
          put("three", 3);
          put("duplicate", 2);
        }};
      
        // when
        String keyForValueTwo = mapSearch.getKeyByValue(map, 2);
        String keyForValueFour = mapSearch.getKeyByValue(map, 4);
      
        // then
        assertAll(
            () -> assertEquals("two", keyForValueTwo),
            () -> assertNull(keyForValueFour)
        );
      }

       

      5. 조건에 부합하는 첫 번째 엔트리 조회

      주어진 조건에 부합하는 첫 번째 엔트리를 조회할 때, filter를 사용하여 조건에 맞는 요소를 찾습니다.
      /**
       * 주어진 조건에 부합하는 첫 번째 엔트리를 조회
       *
       * @param map       검색할 맵
       * @param condition 검색 조건
       * @param <K>       키의 타입
       * @param <V>       값의 타입
       * @return 조건에 부합하는 첫 번째 엔트리를 포함하는 {@code Optional}, 조건에 부합하는 엔트리가 없으면 빈 {@code Optional}
       */
      public <K, V> Optional<Map.Entry<K, V>> findEntryByCondition(
          Map<K, V> map, Predicate<Entry<K, V>> condition) {
        return map.entrySet()
            .stream()
            .filter(condition)
            .findFirst();
      }
       
      위의 코드에서 filter 메서드는 주어진 Predicate 조건에 맞는 엔트리를 걸러냅니다. 그런 다음, findFirst 메서드를 사용하여 첫 번째 엔트리를 반환합니다. 
       
      단위 테스트
      @DisplayName("findEntryByCondition: 조건에 부합하는 첫 번째 엔트리 찾기")
      @Test
      void testFindEntryByCondition() {
      
        // given
        Map<String, Integer> map = new LinkedHashMap<>() {{
          put("one", 1);
          put("two", 2);
          put("three", 3);
        }};
        Predicate<Map.Entry<String, Integer>> condition = entry -> entry.getValue() > 1;
      
        // when
        Optional<Map.Entry<String, Integer>> entry = mapSearch.findEntryByCondition(map, condition);
      
        // then
        assertAll(
            () -> assertTrue(entry.isPresent()),
            () -> assertEquals("two", entry.get().getKey())
        );
      }
       

      6. 패턴 조건에 맞는 첫 번째 엔트리 조회

      주어진 패턴 조건에 맞는 값을 가진 첫 번째 엔트리를 조회할 때, filter를 사용하여 조건에 맞는 요소를 찾습니다.
      /**
       * 주어진 패턴 조건에 맞는 값을 가진 첫 번째 엔트리를 조회
       *
       * @param map              검색할 맵
       * @param patternCondition 검색할 패턴 조건
       * @param <K>              키의 타입
       * @param <V>              값의 타입
       * @return 패턴에 부합하는 값을 가진 첫 번째 엔트리를 포함하는 {@code Optional}, 패턴 조건에 맞는 엔트리가 없으면 빈 {@code Optional}
       */
      public <K, V> Optional<Map.Entry<K, V>> findEntryByPattern(
          Map<K, V> map, Predicate<V> patternCondition) {
        return map.entrySet()
            .stream()
            .filter(entry -> patternCondition.test(entry.getValue()))
            .findFirst();
      }​
      위의 코드에서 filter 메서드는 주어진 패턴 조건에 맞는 값을 가진 엔트리를 걸러냅니다. Predicate 조건은 entry.getValue()를 테스트하여 이를 확인합니다. 그런 다음, findFirst 메서드를 사용하여 첫 번째 엔트리를 반환합니다.
       
      단위 테스트
      @DisplayName("findEntryByPattern: 패턴에 맞는 값을 가진 첫 번째 엔트리 찾기")
      @Test
      void testFindEntryByPattern() {
      
        // given
        Map<String, Integer> map = Map.of("one", 1, "two", 2, "three", 3);
        Predicate<Integer> patternCondition = value -> value > 2;
      
        // when
        Optional<Map.Entry<String, Integer>> entry = mapSearch.findEntryByPattern(map,
            patternCondition);
      
        // then
        assertAll(
            () -> assertTrue(entry.isPresent()),
            () -> assertEquals("three", entry.get().getKey())
        );
      }

       

      소스 코드는 Github Repository- https://github.com/tychejin1218/blog/tree/main/java-collection 프로젝트를 참조하세요.

      반응형

      댓글

    Designed by Tistory.