Merge branch 'v6-dev' into refactor-stream

# Conflicts:
#	hutool-core/src/main/java/cn/hutool/core/stream/EasyStream.java
This commit is contained in:
huangchengxing 2022-09-07 09:33:09 +08:00
commit 89c3f3c4bc
2 changed files with 31 additions and 9 deletions

View File

@ -1258,13 +1258,7 @@ public class MapUtil extends MapGetUtil {
final Map<K, List<V>> map = new HashMap<>(); final Map<K, List<V>> map = new HashMap<>();
for (final Map.Entry<K, V> pair : entries) { for (final Map.Entry<K, V> pair : entries) {
final List<V> values; final List<V> values = map.computeIfAbsent(pair.getKey(), k -> new ArrayList<>());
if (map.containsKey(pair.getKey())) {
values = map.get(pair.getKey());
} else {
values = ListUtil.of();
map.put(pair.getKey(), values);
}
values.add(pair.getValue()); values.add(pair.getValue());
} }
return map; return map;

View File

@ -150,6 +150,34 @@ public class CollectorUtil {
return groupingBy(classifier, Collectors.toList()); return groupingBy(classifier, Collectors.toList());
} }
/**
* 对null友好的 toMap 操作的 {@link Collector}实现默认使用HashMap
*
* @param keyMapper 指定map中的key
* @param valueMapper 指定map中的value
* @param <T> 实体类型
* @param <K> map中key的类型
* @param <U> map中value的类型
* @return 对null友好的 toMap 操作的 {@link Collector}实现
*/
public static <T, K, U> Collector<T, ?, Map<K, U>> toMap(final Function<? super T, ? extends K> keyMapper,
final Function<? super T, ? extends U> valueMapper) {
return toMap(keyMapper, valueMapper, (l, r) -> r);
}
/**
* 对null友好的 toMap 操作的 {@link Collector}实现默认使用HashMap
*
* @param keyMapper 指定map中的key
* @param <T> 实体类型
* @param <K> map中key的类型
* @return 对null友好的 toMap 操作的 {@link Collector}实现
*/
public static <T, K> Collector<T, ?, Map<K, T>> toMap(final Function<? super T, ? extends K> keyMapper) {
return toMap(keyMapper, Function.identity());
}
/** /**
* 对null友好的 toMap 操作的 {@link Collector}实现默认使用HashMap * 对null友好的 toMap 操作的 {@link Collector}实现默认使用HashMap
* *
@ -162,8 +190,8 @@ public class CollectorUtil {
* @return 对null友好的 toMap 操作的 {@link Collector}实现 * @return 对null友好的 toMap 操作的 {@link Collector}实现
*/ */
public static <T, K, U> Collector<T, ?, Map<K, U>> toMap(final Function<? super T, ? extends K> keyMapper, public static <T, K, U> Collector<T, ?, Map<K, U>> toMap(final Function<? super T, ? extends K> keyMapper,
final Function<? super T, ? extends U> valueMapper, final Function<? super T, ? extends U> valueMapper,
final BinaryOperator<U> mergeFunction) { final BinaryOperator<U> mergeFunction) {
return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new); return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new);
} }