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
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
4            .sorted()
5            .findFirst();

Compliant example

1Optional<String> MinCompliant(final Collection<String> col) {
2    // Compliant: uses min, max methods over sorted and findFirst stream methods.
3    return;