With a Stream<T>
and a Comparator<? super T>
,
Stream<T> s;
Comparator<? super T> c;
is
s.sorted(c).findFirst();
equals to equivalent to
s.min(c);
?
sorted. Returns a stream consisting of the elements of this stream, sorted according to natural order. If the elements of this stream are not Comparable , a java. lang.
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
Java Comparator interface is used to order the objects of a user-defined class. This interface is found in java. util package and contains 2 methods compare(Object obj1,Object obj2) and equals(Object element).
Logically, both code snippets return the same result. However, sorted
takes more time and potentially more memory, because comparator-based sorting is O(n*log n) and needs O(n) space to avoid sorting in place, while searching for min
is O(n), and needs O(1) space.
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