Unguarded first element access (ARCH4078)
هذا المحتوى غير متوفر بلغتك بعد.
Key java.performance.first-or-default-null · Severity warning · Category performance
Accessing the first element of a filtered result without an empty check throws when the result is empty. The Optional from findFirst should be handled safely.
Incorrect
Section titled “Incorrect”User admin = users.stream() .filter(User::isAdmin) .collect(toList()) .get(0);return admin.getName();Correct
Section titled “Correct”return users.stream() .filter(User::isAdmin) .findFirst() .map(User::getName) .orElse("none");Use findFirst() instead of get(0) and resolve the returned Optional with orElse.