All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.azbh111.utils.java.map.MapUtils Maven / Gradle / Ivy

The newest version!
/*
 * Copyright (c) 2014-2019, Deepspring Healthcare Inc. All rights reserved.
 */

package com.github.azbh111.utils.java.map;


import com.github.azbh111.utils.java.annotation.Nonnull;
import com.github.azbh111.utils.java.annotation.Nullable;
import com.github.azbh111.utils.java.iterable.IterableUtils;

import java.util.*;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.BinaryOperator;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @author pyz
 * @date 2018/8/27 下午6:29
 */
public class MapUtils {


    /**
     * 遍历src,若target中不含遍历的key,则把对应的kv放入target中
     *
     * @param src
     * @param target
     * @param 
     * @param 
     */
    public static  void putAllIfAbsent(Map src, Map target) {
        src.forEach((k, v) -> {
            target.putIfAbsent(k, v);
        });
    }

    /**
     * 遍历src,若target中不含遍历的key,则使用generator生成v,并把kv放入target中
     *
     * @param src
     * @param target
     * @param generator
     * @param 
     * @param 
     * @param 
     */
    public static  void putOrCreateAllIfAbsent(Map src, Map target, BiFunction generator) {
        src.forEach((k, v) -> {
            target.computeIfAbsent(k, key -> generator.apply(k, v));
        });
    }


    /**
     * 按给定映射,将map分成多个map
     *
     * @param map
     * @param groupMapper
     * @param 
     * @param 
     * @param 
     * @return
     */
    public static  Map> groupBy(Map map, BiFunction groupMapper) {
        Map> resultMap = new HashMap<>();
        map.forEach((k, v) -> {
            GroupKey key = groupMapper.apply(k, v);
            MapUtils.getOrCreate(resultMap, key, HashMap::new)
                    .put(k, v);
        });
        return resultMap;
    }

    public static  List toList(Map map, BiFunction mapper) {
        return map.entrySet()
                .stream()
                .map(entry -> mapper.apply(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());
    }

    public static  Map extract(Map map, Iterable keys) {
        return IterableUtils.toStream(keys)
                .filter(map::containsKey)
                .collect(Collectors.toMap(k -> k, k -> map.get(k)));
    }

    /**
     * 用指定keys从map中提取value,返回values
     *
     * @param map
     * @param keys
     * @param 
     * @param 
     * @return
     */
    public static  List extractValueList(Map map, Iterable keys) {
        return IterableUtils.toStream(keys)
                .filter(map::containsKey)
                .map(map::get)
                .collect(Collectors.toList());
    }

    /**
     * 用指定keys从map中提取value,返回values
     *
     * @param map
     * @param keys
     * @param 
     * @param 
     * @return
     */
    public static  Set extractValueSet(Map map, Iterable keys) {
        return IterableUtils.toStream(keys)
                .filter(map::containsKey)
                .map(map::get)
                .collect(Collectors.toSet());
    }

    public static  V getOrCreate(Map map, K key, Supplier valueCreator) {
        V value = map.get(key);
        if (value == null) {
            value = valueCreator.get();
            map.put(key, value);
        }
        return value;
    }

    public static  Map computeKey(Map src, BiFunction keyMapper) {
        return compute(src, keyMapper, (k, v) -> v);
    }

    public static  Map computeValue(Map src, BiFunction valueMapper) {
        return compute(src, (k, v) -> k, valueMapper);
    }

    public static  Map compute(Map src, BiFunction keyMapper, BiFunction valueMapper) {
        Map result = new HashMap<>();
        if (src == null) {
            return result;
        }
        src.forEach((k, v) -> {
            R replace = result.put(keyMapper.apply(k, v), valueMapper.apply(k, v));
            if (replace != null) {
                // 计算后的key不能重复
                throw new IllegalStateException(String.format("Duplicate key %s", k));
            }
        });
        return result;
    }

    public static  void removeIf(Map map, BiPredicate test) {
        Iterator> it = map.entrySet().iterator();
        Map.Entry en;
        while (it.hasNext()) {
            en = it.next();
            if (test.test(en.getKey(), en.getValue())) {
                it.remove();
            }
        }
    }

    public static  Map filter(Map map, BiPredicate test) {
        Map result = new HashMap<>();
        map.forEach((k, v) -> {
            if (test.test(k, v)) {
                result.put(k, v);
            }
        });
        return result;
    }

    /**
     * 取一个value
     *
     * @param statusMap
     * @param 
     * @param 
     * @return
     */
    public static  V anyValue(Map statusMap) {
        Map.Entry entry = anyEntry(statusMap);
        return entry == null ? null : entry.getValue();
    }

    /**
     * 取一个key
     *
     * @param statusMap
     * @param 
     * @param 
     * @return
     */
    public static  K anyKey(Map statusMap) {
        Map.Entry entry = anyEntry(statusMap);
        return entry == null ? null : entry.getKey();
    }

    public static  Map.Entry anyEntry(Map statusMap) {
        if (statusMap == null) {
            return null;
        }
        Iterator> it = statusMap.entrySet().iterator();
        if (!it.hasNext()) {
            return null;
        }
        return it.next();
    }

    public static  boolean isNullOrEmpty(Map map) {
        return map == null || map.size() == 0;
    }

    /**
     * 翻转map 如果翻转后key有冲突,会抛异常
     *
     * @param map
     * @param 
     * @param 
     * @return
     */
    public static  Map reverse(Map map) {
        return reverse(map, null);
    }

    /**
     * 翻转map
     *
     * @param map
     * @param mergeFunction 如果不传,且key有冲突,会抛异常
     * @param 
     * @param 
     * @return
     */
    public static  Map reverse(@Nonnull Map map, @Nullable BinaryOperator mergeFunction) {
        Map reverseMap = new HashMap<>();
        for (Map.Entry kvEntry : map.entrySet()) {
            K replaceK = reverseMap.put(kvEntry.getValue(), kvEntry.getKey());
            if (replaceK == null) continue;
            if (mergeFunction == null) throw new IllegalStateException(String.format("Duplicate key %s", kvEntry.getValue()));
            K finalK = mergeFunction.apply(replaceK, kvEntry.getKey());
            if (finalK != replaceK) reverseMap.put(kvEntry.getValue(), finalK);
        }
        return reverseMap;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy