What's the best way of getting the Kth largest element in a DoubleStream in java?
I know we can do .max().getDouble() to get the largest element.
What's the best way of getting the Kth largest element in a DoubleStream in java?
I know we can do .max().getDouble() to get the largest element.
OptionalDouble kthLargest = stream
.map(i -> -i) // Trick to sort in reverse order
.sorted()
.distinct() // Remove duplicates
.map(i -> -i)
.skip(k - 1)
.findFirst();
doubleStream.boxed()
.sorted(Comparator.reverseOrder())
.skip(k - 1)
.findFirst()
.orElse(null);
Will give you the kth largest element, or null
if there are less than k elements in the stream.
Sort the stream, transform it to an array and get the item at array.length-k.
Example:
private static double getKth(DoubleStream ds, int k) {
double[] array = ds
.sorted()
.toArray();
return array[array.length-k];
}
You should add validation to make sure k
has a legit value
Once you have DoubleStream
, make it sorted()
in reverse order (DESC). Then limit(k)
and sort ASC and take the first
.
.boxed()
.distinct() //in case you want to ignore repeating values
.sorted(Comparator.reverseOrder())
.limit(k)
.sorted()
.findFirst());