Aller au contenu

Unguarded first element access (ARCH4078)

Ce contenu n’est pas encore disponible dans votre langue.

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.

User admin = users.stream()
.filter(User::isAdmin)
.collect(toList())
.get(0);
return admin.getName();
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.