Using Stream::min
or Stream::max
is more efficient than sorting and getting the first element in a stream. The former has linear time complexity while the latter has higher time complexity.
1Optional<String> streamSortThenFindFirstNoncompliant(final Collection<String> col) {
2 // Noncompliant: uses sorted and findFirst over min, max stream methods.
3 return col.stream()
4 .sorted()
5 .findFirst();
6}
1Optional<String> MinCompliant(final Collection<String> col) {
2 // Compliant: uses min, max methods over sorted and findFirst stream methods.
3 return col.stream().min(String::compareTo);
4}