/* package whatever; // don't place package name! */
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.Collector;
import java.util.stream.Stream;
public class Main {
public static void main
(String[] args
) { ArrayList<MyCustomObject> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
list.add(new MyCustomObject(i));
}
}
Comparator
<MyCustomObject
> compare
= Comparator.
comparing(MyCustomObject
::getIntField
); class Intermediate {
MyCustomObject value = null;
List<MyCustomObject> objects = new ArrayList<>();
void add(MyCustomObject c) {
if (objects.isEmpty()) {
value = c;
} else {
int compareResult = compare.compare(c, objects.get(0));
if (compareResult > 0) {
// new max found
System.
out.
println("new max " + c.
intField + ", dropping " + objects.
size() + " objects"); value = c;
objects.clear();
} else if (compareResult < 0) {
return;
}
}
objects.add(c);
}
}
BinaryOperator<Intermediate> combiner = (i1, i2) -> {
System.
out.
printf("combining %d and %d%n", i1.
value, i2.
value); Intermediate result = new Intermediate();
Optional<MyCustomObject> max = Stream.of(i1, i2).filter(i -> !i.objects.isEmpty())
.map(i -> i.objects.get(0)).max(compare);
max.ifPresent(m -> {
if (compare.compare(i1.value, m) == 0) {
result.objects.addAll(i1.objects);
}
if (compare.compare(i2.value, m) == 0) {
result.objects.addAll(i2.objects);
}
});
return result;
};
Collector<MyCustomObject, Intermediate, List<MyCustomObject>> collector = Collector.of(Intermediate::new,
Intermediate::add, combiner, i -> i.objects);
System.
out.
println(list.
stream().
collect(collector
)); }
static class MyCustomObject {
private int intField;
MyCustomObject(int field) {
intField = field;
}
public int getIntField() {
return intField;
}
@Override
}
}
}