public class ZYMapUtils extends MapUtil {
// 根据key收藏model
public static <V> void flushMap(String key, Map<String, List<V>> map, V v) {
List<V> vs = map.containsKey(key) ? map.get(key) : new ArrayList<>();
vs.add(v);
map.put(key, vs);
}
// map转换k或value
public static <A, B, C, D> Map<A, B> map2map(Map<C, D> sourceMap, Function<C, A> keyFunction,
Function<D, B> valueFunction) {
Map<A, B> targetMap = new HashMap<>();
if (null == sourceMap || sourceMap.isEmpty()) {
return targetMap;
}
sourceMap.forEach((k, v) -> {
if (ZYStrUtils.isNotNull(v)) {
targetMap.put(keyFunction.apply(k), valueFunction.apply(v));
}
});
return targetMap;
}
// map key转换
public static <A, C, D> Map<A, D> map2mapKey(Map<C, D> sourceMap, Function<C, A> keyFunction) {
return map2map(sourceMap, keyFunction, v -> v);
}
public static <A, B, D> Map<A, B> map2mapValue(Map<A, D> sourceMap, Function<D, B> valueFunction) {
return map2map(sourceMap, k -> k, valueFunction);
}
// 收藏list实体的某个字段
public static <T> Map<String, List<String>> map2mapField(Map<String, List<T>> sourceMap, Function<T, String> valueFunction) {
Map<String, List<String>> map = new HashMap<>();
if (isEmptyMap(sourceMap)) {
return map;
}
sourceMap.forEach((k, ts) -> {
List<java.lang.String> strings = ZYListUtils.collectField(ts, valueFunction);
map.put(k, strings);
});
return map;
}
// 统计某个字段出现的次数
public static <T> Map<String, Integer> countField(List<T> ts, Function<T, String> fieldValueFun) {
Map<String, Integer> countMap = new HashMap<>();
ts.forEach(t -> {
String fieldValue = fieldValueFun.apply(t);
if (ZYStrUtils.isNotNull(fieldValue)) {
Integer count = countMap.get(fieldValue);
countMap.put(fieldValue, null == count ? 1 : count + 1);
}
});
return countMap;
}
public static <T> Map<String, Integer> countFields(List<T> ts, Function<T, List<String>> fieldValueFun) {
Map<String, Integer> countMap = new HashMap<>();
ts.forEach(t -> toCount(fieldValueFun, countMap, t));
return countMap;
}
private static <T> void toCount(Function<T, List<String>> fieldValueFun, Map<String, Integer> countMap, T t) {
List<String> fieldValues = fieldValueFun.apply(t);
if (null != fieldValues && fieldValues.size() > 0) {
fieldValues.forEach(fieldValue -> {
if (ZYStrUtils.isNotNull(fieldValue)) {
Integer count = countMap.get(fieldValue);
countMap.put(fieldValue, null == count ? 1 : count + 1);
}
});
}
}
public static <K, V> boolean isEmptyMap(Map<K, V> map) {
return null == map || map.isEmpty();
}
public static <K, V> boolean isNotEmptyMap(Map<K, V> map) {
return !isEmptyMap(map);
}
}
几个简单的map操作工具类
最新推荐文章于 2024-08-01 16:53:57 发布
这个Java类提供了一系列静态方法,用于处理Map数据结构。包括根据key收集Model,转换Map的键或值,转换Map的键或值的功能,以及统计List中对象字段出现的次数等集合操作。
摘要由CSDN通过智能技术生成