public class ConverterUtil {
public static <T, K> Map<K, T> toMap(Collection<T> data, Function<? super T, ? extends K> keyMapper) { return toMap(data, keyMapper, Function.identity()); }
private static <K, T> Map<K, T> toMap(Collection<T> data, Function<? super T, ? extends K> keyMapper, Function<T, T> valueMapper) { return toMap(data, keyMapper, valueMapper, pickSecond()); }
public static <T, K, V> Map<K, V> toMap(Collection<T> data, Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper, BinaryOperator<V> mergerFunction) { if (CollUtil.isEmpty(data)) { return Collections.emptyMap(); }
return data.stream().collect( Collectors.toMap(keyMapper, valueMapper, mergerFunction) ); }
public static <K, V, C> Map<K, C> convertMapValue(Map<K, V> map, BiFunction<K, V, C> valueFunction) { return convertMapValue(map, valueFunction, pickSecond()); }
public static <K, V, C> Map<K, C> convertMapValue(Map<K, V> map, BiFunction<K, V, C> valueFunction, BinaryOperator<C> mergeFunction) { if (CollUtil.isEmpty(map)) { return Collections.emptyMap(); }
return map.entrySet().stream().collect( Collectors.toMap( Map.Entry::getKey, e -> valueFunction.apply(e.getKey(), e.getValue()), mergeFunction ) ); }
public static <T> BinaryOperator<T> pickFirst() { return (k1, k2) -> k1; }
public static <T> BinaryOperator<T> pickSecond() { return (k1, k2) -> k2; }
public static <T> List<T> toList(Collection<T> data) { if (CollUtil.isEmpty(data)) { return Collections.emptyList(); }
if (data instanceof List<T>) { return (List<T>) data; }
return new ArrayList<>(data); }
public static <T> Set<T> toSet(Collection<T> data) { if (CollUtil.isEmpty(data)) { return Collections.emptySet(); }
if (data instanceof Set<T>) { return (Set<T>) data; }
return new HashSet<>(data); }
public static <T, R> List<R> map(List<T> data, Function<T, R> mapper) { return data.stream().map(mapper).collect(Collectors.toList()); }
public static <T, R> Set<R> map(Set<T> data, Function<T, R> mapper) { return data.stream().map(mapper).collect(Collectors.toSet()); }
public static <T, R> List<R> mapToList(Collection<T> data, Function<T, R> mapper) { return data.stream().map(mapper).collect(Collectors.toList()); }
public static <T, R> Set<R> mapToSet(Collection<T> data, Function<T, R> mapper) { return data.stream().map(mapper).collect(Collectors.toSet()); }
}
|