001/** 002 * Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package com.mybatisflex.core.util; 017 018import java.util.*; 019import java.util.function.Function; 020 021 022public class CollectionUtil { 023 024 025 public static boolean isEmpty(Collection<?> collection) { 026 return collection == null || collection.isEmpty(); 027 } 028 029 030 public static boolean isNotEmpty(Collection<?> collection) { 031 return !isEmpty(collection); 032 } 033 034 035 public static boolean isEmpty(Map<?, ?> map) { 036 return map == null || map.isEmpty(); 037 } 038 039 040 public static boolean isNotEmpty(Map<?, ?> map) { 041 return !isEmpty(map); 042 } 043 044 /** 045 * 合并 list 046 */ 047 public static <T> List<T> merge(List<T> list, List<T> other) { 048 if (list == null && other == null) { 049 return new ArrayList<>(); 050 } else if (isEmpty(other) && list != null) { 051 return list; 052 } else if (isEmpty(list)) { 053 return other; 054 } 055 List<T> newList = new ArrayList<>(list); 056 newList.addAll(other); 057 return newList; 058 } 059 060 061 public static <K, V> HashMap<K, V> newHashMap() { 062 return new HashMap<>(); 063 } 064 065 /** 066 * 主要是用于修复 concurrentHashMap 在 jdk1.8 下的死循环问题 067 * 068 * @see <a href="https://bugs.openjdk.org/browse/JDK-8161372">https://bugs.openjdk.org/browse/JDK-8161372</a> 069 */ 070 public static <K, V> V computeIfAbsent(Map<K, V> concurrentHashMap, K key, Function<? super K, ? extends V> mappingFunction) { 071 V v = concurrentHashMap.get(key); 072 if (v != null) { 073 return v; 074 } 075 return concurrentHashMap.computeIfAbsent(key, mappingFunction); 076 } 077 078 public static <T> Set<T> newHashSet(T... elements) { 079 return new HashSet<>(Arrays.asList(elements)); 080 } 081 082 public static <T> List<T> newArrayList(T... elements) { 083 return new ArrayList<>(Arrays.asList(elements)); 084 } 085 086}