MapUtil.java

  1. /*
  2.  *    Copyright 2009-2023 the original author or authors.
  3.  *
  4.  *    Licensed under the Apache License, Version 2.0 (the "License");
  5.  *    you may not use this file except in compliance with the License.
  6.  *    You may obtain a copy of the License at
  7.  *
  8.  *       https://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  *    Unless required by applicable law or agreed to in writing, software
  11.  *    distributed under the License is distributed on an "AS IS" BASIS,
  12.  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  *    See the License for the specific language governing permissions and
  14.  *    limitations under the License.
  15.  */
  16. package org.apache.ibatis.util;

  17. import java.util.AbstractMap;
  18. import java.util.Map;
  19. import java.util.Map.Entry;
  20. import java.util.function.Function;

  21. public class MapUtil {
  22.   /**
  23.    * A temporary workaround for Java 8 specific performance issue JDK-8161372 .<br>
  24.    * This class should be removed once we drop Java 8 support.
  25.    *
  26.    * @see <a href=
  27.    *      "https://bugs.openjdk.java.net/browse/JDK-8161372">https://bugs.openjdk.java.net/browse/JDK-8161372</a>
  28.    */
  29.   public static <K, V> V computeIfAbsent(Map<K, V> map, K key, Function<K, V> mappingFunction) {
  30.     V value = map.get(key);
  31.     if (value != null) {
  32.       return value;
  33.     }
  34.     return map.computeIfAbsent(key, mappingFunction);
  35.   }

  36.   /**
  37.    * Map.entry(key, value) alternative for Java 8.
  38.    */
  39.   public static <K, V> Entry<K, V> entry(K key, V value) {
  40.     return new AbstractMap.SimpleImmutableEntry<>(key, value);
  41.   }

  42.   private MapUtil() {
  43.   }
  44. }