I have a Collection<List<SomeObject>> values
How can I find the collection with the largest list using Streams?
I have tried something like this, but it doesn't quite work
values.stream().max(e -> e.stream().max(List::size).get()).get()
But I get compilation error. Any ideas?
Calling stream() method on the list to get a stream of values from the list. Calling mapToInt(value -> value) on the stream to get an Integer Stream. Calling max() method on the stream to get the max value.
max() method. The idea is to convert the list into a Stream and call Stream#max() that accepts a Comparator to compare items in the stream against each other to find the maximum element, and returns an Optional containing the maximum element in the stream according to the provided Comparator .
No storage. Streams don't have storage for values; they carry values from a source (which could be a data structure, a generating function, an I/O channel, etc) through a pipeline of computational steps.
I think you want
values.stream().max(Comparator.comparingInt(List::size)).get()
If you need duplicates, the best solution I can think of would be something like
values.stream()
.collect(Collector.of(
ArrayList::new,
(List<List<SomeObject>> best, List<SomeObject> elem) -> {
if (best.isEmpty()) {
best.add(elem);
} else if (best.get(0).size() < elem.size()) {
best.clear();
best.add(elem);
}
},
(best1, best2) -> {
if (best1.isEmpty() || best2.isEmpty()
|| best1.get(0).size() == best2.get(0).size()) {
best1.addAll(best2);
return best1;
} else if (best1.get(0).size() > best2.get(0).size()) {
return best1;
} else {
return base2;
}
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With