您可以为 Group by 实现 Utility 类,如下所示。
public class GroupByUtility<T> implements Consumer<T> {
public static <T extends Comparable<? super T>> Collector<T, ?, GroupByUtility<T>>
statistics() {
return statistics(Comparator.<T>naturalOrder());
}
public static <T> Collector<T, ?, GroupByUtility<T>>
statistics(Comparator<T> comparator) {
Objects.requireNonNull(comparator);
return Collector.of(() -> new GroupByUtility<>(comparator),
GroupByUtility::accept, GroupByUtility::merge);
}
private final Comparator<T> c;
private T min, max;
private long count;
public GroupByUtility(Comparator<T> comparator) {
c = Objects.requireNonNull(comparator);
}
public void accept(T t) {
if (count == 0) {
count = 1;
min = t;
max = t;
} else {
if (c.compare(min, t) > 0) min = t;
if (c.compare(max, t) < 0) max = t;
count++;
}
}
public GroupByUtility<T> merge(GroupByUtility<T> s) {
if (s.count > 0) {
if (count == 0) {
count = s.count;
min = s.min;
max = s.max;
} else {
if (c.compare(min, s.min) > 0) min = s.min;
if (c.compare(max, s.max) < 0) max = s.max;
count += s.count;
}
}
return this;
}
public long getCount() {
return count;
}
public T getMin() {
return min;
}
public T getMax() {
return max;
}
}
然后从您的代码中调用该实用程序类方法以获取 Count,Min and Max 按字段指定为 group By
List<DocumentsBookdata> documentsBookdata=new ArrayList();
Map<Long, GroupByUtility<DocumentsBookdata>> maxMap = documentsBookdata.stream()
.collect(Collectors.groupingBy(o -> o.getBookId(),
GroupByUtility.statistics(Comparator.comparing(o -> o.getPublisherName()))));
return maxMap.entrySet().stream().map(obj->obj.getValue().getCount()).collect(Collectors.toList());