前言
工具类用于对一组数据进行一系列操作如映射、分组、排序后,返回结果。
package com.iscas.supervision.util;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ResultUtil {
public static <T, K, V extends Comparable<? super V>, R> Map getResult(List<T> data, Function<T, K> key, Function<T, V> value, Function<V, R> valueCallBack) {
return getResult(data, (Comparator<T>) null, key, value, valueCallBack);
}
public static <T, K, V extends Comparable<? super V>, R> Map getResult(List<T> data, Comparator<T> comparator, Function<T, K> key, Function<T, V> value, Function<V, R> valueCallBack) {
return getResult(data, null, comparator, key, value, valueCallBack);
}
public static <T, G, K, V extends Comparable<? super V>, R> Map getResult(List<T> data, Function<T, G> groupBy, Function<T, K> key, Function<T, V> value, Function<V, R> valueCallBack) {
return getResult(data, groupBy, null, key, value, valueCallBack);
}
/**
* 适用于返回值是两个字段,即作为map的key和value
*
* @param data 源数据集合
* @param groupBy 分组字段
* @param comparator 排序字段,默认按value倒序排序
* @param key map的key
* @param value map的value
* @param <T> 源数据类型
* @param valueCallBack value的后处理回调
* @return 排序后的数据
*/
public static <T, G, K, V extends Comparable<? super V>, R> Map getResult(List<T> data, Function<T, G> groupBy, Comparator<T> comparator, Function<T, K> key, Function<T, V> value, Function<V, R> valueCallBack) {
if (data == null || key == null || value == null) {
return Collections.emptyMap();
}
Stream<T> stream = data.stream().filter(t -> value.apply(t) != null);
if (comparator != null) {
stream = stream.sorted(comparator);
} else {
//默认按value倒序排序
stream = stream.sorted(Comparator.comparing(value, Comparator.reverseOrder()));
}
if (groupBy == null) {
//不用分组
return stream.collect(Collectors.toMap(key, value.andThen(valueCallBack), (oldValue, newValue) -> newValue != null ? newValue : oldValue, LinkedHashMap::new));
} else {
//需要分组
return stream.collect(Collectors.groupingBy(groupBy, Collectors.toMap(key, value.andThen(valueCallBack), (oldValue, newValue) -> newValue != null ? newValue : oldValue, LinkedHashMap::new)));
}
}
}