com.mogudiandian.util.stream.ForceToMapCollector Maven / Gradle / Ivy
package com.mogudiandian.util.stream;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
/**
* 强制toMap收集器
* 直接使用默认的Collectors.toMap会出现两个问题
* 1、key重复时抛异常
* 2、value为空时抛异常
* 因此封装了这个工具解决这两个问题
*
* 使用方式:
*
* int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
* Map map = Arrays.stream(arr).boxed().collect(ForceToMapCollector.collect(Functional.identity(), x -> x % 2 == 0));
* System.out.println(map);
*
*
* @param stream中元素的类型
* @param key的类型
* @param value的类型
* @author Joshua Sun
* @since 1.0.0
*/
public final class ForceToMapCollector implements Collector, Map> {
private Function super T, ? extends K> keyMapper;
private Function super T, ? extends V> valueMapper;
public ForceToMapCollector(Function super T, ? extends K> keyMapper,
Function super T, ? extends V> valueMapper) {
super();
this.keyMapper = keyMapper;
this.valueMapper = valueMapper;
}
/**
* 创建ForceToMap收集器实例
* @param keyMapper key的映射器
* @param valueMapper value的映射器
* @param stream中元素的类型
* @param key的类型
* @param value的类型
* @return ForceToMapCollector收集器
*/
public static ForceToMapCollector collect(Function keyMapper, Function valueMapper) {
return new ForceToMapCollector<>(keyMapper, valueMapper);
}
/**
* 创建ForceToMap收集器实例 收集后map的value类型为流的类型
* @param keyMapper key的映射器
* @param stream中元素的类型
* @param key的类型
* @return ForceToMapCollector收集器
*/
public static ForceToMapCollector collect(Function keyMapper) {
return new ForceToMapCollector<>(keyMapper, Function.identity());
}
@Override
public BiConsumer