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

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 keyMapper; private Function valueMapper; public ForceToMapCollector(Function keyMapper, Function 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, T> accumulator() { return (map, element) -> map.put(keyMapper.apply(element), valueMapper.apply(element)); } @Override public Supplier> supplier() { return HashMap::new; } @Override public BinaryOperator> combiner() { return (x, y) -> { x.putAll(y); return x; }; } @Override public Function, Map> finisher() { return Function.identity(); } @Override public Set characteristics() { return Collections.unmodifiableSet(EnumSet.of(Characteristics.IDENTITY_FINISH)); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy