As Collectors.toMap(keyMapper, valueMapper)
uses a throwing merger to handle multiple entries with the same key it is easy:
List<User> users = new LinkedList<>();
users.add(new User(1, "User1"));
users.add(new User(2, "User2"));
users.add(new User(3, "User3"));
int id = 1;
User match = Optional.ofNullable(users.stream()
.filter(user -> user.getId() == id)
.collect(Collectors.toMap(User::getId, Function.identity()))
.get(id)).get();
You will get a IllegalStateException
for duplicate keys. But at the end I am not sure if the code would not be even more readable using an if
.