Nice suggestion in comment from @Holger:
Optional<User> match = users.stream()
.filter((user) -> user.getId() > 1)
.reduce((u, v) -> { throw new IllegalStateException("More than one ID found") });
The exception is thrown by Optional#get
, but if you have more than one element that won't help. You could collect the users in a collection that only accepts one item, for example:
User match = users.stream().filter((user) -> user.getId() > 1)
.collect(toCollection(() -> new ArrayBlockingQueue<User>(1)))
.poll();
which throws a java.lang.IllegalStateException: Queue full
, but that feels too hacky.
Or you could use a reduction combined with an optional:
User match = Optional.ofNullable(users.stream().filter((user) -> user.getId() > 1)
.reduce(null, (u, v) -> {
if (u != null && v != null)
throw new IllegalStateException("More than one ID found");
else return u == null ? v : u;
})).get();
The reduction essentially returns:
The result is then wrapped in an optional.
But the simplest solution would probably be to just collect to a collection, check that its size is 1 and get the only element.