Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is min(Comparator) equals to sorted(Comparator).findFirst()?

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);

?

like image 930
Jin Kwon Avatar asked Jul 29 '15 03:07

Jin Kwon


People also ask

What is the purpose of sorted method of stream in Java 8?

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.

What does .stream do in Java?

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.

What is comparator comparing in Java?

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).


1 Answers

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.

like image 179
Sergey Kalinichenko Avatar answered Sep 27 '22 17:09

Sergey Kalinichenko