public class StreamUtils {
/**
* 根据指定条件使用Stream查询List当中重复的实体,并且返回实体
* @param list
* @param function 指定查詢條件
* @param <E>
* @param <R>
* @return
*/
public static <E, R> List<E> getDuplicateElements(List<E> list, Function<E, R> function) {
Map<R, List<E>> collect = list.stream().collect(Collectors.groupingBy(function));
return collect.entrySet().stream().filter(entry -> entry.getValue().size() > 1).flatMap(entry -> entry.getValue().stream()).collect(Collectors.toList());
}
/**
* 使用Stream查询List当中实体的某个属性重复值有哪些
*/
// 方法
public static <E, R> List<R> getDuplicateValue(List<E> list, Function<E, R> function) {
Map<R, Long> frequencies = list.stream().collect(Collectors.groupingBy(function, Collectors.counting()));
return frequencies.entrySet().stream()
.filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey()).collect(Collectors.toList());
}
/**
* List<List<T>> 转化为List<T>
*/
public static <E> List<E> convertListToListList(List<List<E>> list) {
List<E> res = list.stream().map(subList -> subList.stream()).flatMap(integerStream -> integerStream).collect(Collectors.toList());
return res;
}
/**
* 给Map的value进行排序
*/
public static <K, V> Map<K, V> sortByMapKey(Map<K, V> map, Comparator<Map.Entry<K, V>> comparator) {
// LinkedHashMap 保证顺序
LinkedHashMap<K, V> collect = map.entrySet().stream()
//.sorted(Map.Entry.comparingByValue())
.sorted(comparator)
.collect(LinkedHashMap::new, ((linkedHashMap, entry) -> linkedHashMap.put(entry.getKey(), entry.getValue())),
LinkedHashMap::putAll);
return collect;
}
/**
* 给List<Map<, Integer>>中的Integer求和
*/
public static <T> Integer sumForListMap(List<Map<T, Integer>> list) {
return list.stream().mapToInt(value -> value.values().stream().mapToInt(Integer::intValue).sum()).sum();
}
/**
* 按照指定条件去重帮助类
* @param keyExtractor
* @param <T>
* @return
*/
private static <T> Predicate<T> distinctByKeyHelp(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> map = new ConcurrentHashMap<>();
return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
/**
* 按照指定条件去重使用
*/
public static <T> List<T> distinctByKey(List<T> list, Function<? super T, Object> keyExtractor) {
return list.stream().filter(distinctByKeyHelp(keyExtractor)).collect(Collectors.toList());
}
}
【Java】Stream的常用封装
最新推荐文章于 2023-11-06 10:18:06 发布