Inefficient use of stream sorting Medium

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.

Detector ID
java/stream-min-max-vs-sort@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-

Noncompliant example

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}

Compliant example

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}