Often, using lists I come to a case like below (lets say a user contains an ID and a name):
List<User> users = loadFromDb();
List<User> lookingForIdResultList = user.stream()
.filter( u -> u.getId() == 1234)
.collect(Collectors.toList())
if(lookingForIdResultList.size() == 0) throw UserNotFoundException()
if(lookingForIdResultList.size() > 1) throw MultipleIdsNotPermittedExcpetion()
User searchedUser = lookingForIdResultList.get(0);
System.out.println("Username is "+ searchedUser.getName())
Is there a way to shorten the validation using the Java Stream API?
This is just an oversimplified example, the problem is generic. I don't want to load users from the database.
The Guava library has Collectors toOptional()
and onlyElement()
for exactly this use-case:
// throws exception if there is not exactly 1 matching user
User searchedUser = users.stream()
.filter(u -> u.getId() == 1234)
.collect(MoreCollectors.onlyElement());