I am trying to use Java 8 Stream
s to find elements in a LinkedList
. I want to guarantee, however, that there is one and only one match to the filter criteria.
Take this code:
public static void main(String[] args) {
LinkedList<User> users = new LinkedList<>();
users.add(new User(1, "User1"));
users.add(new User(2, "User2"));
users.add(new User(3, "User3"));
User match = users.stream().filter((user) -> user.getId() == 1).findAny().get();
System.out.println(match.toString());
}
static class User {
@Override
public String toString() {
return id + " - " + username;
}
int id;
String username;
public User() {
}
public User(int id, String username) {
this.id = id;
this.username = username;
}
public void setUsername(String username) {
this.username = username;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public int getId() {
return id;
}
}
This code finds a User
based on their ID. But there are no guarantees how many User
s matched the filter.
Changing the filter line to:
User match = users.stream().filter((user) -> user.getId() < 0).findAny().get();
Will throw a NoSuchElementException
(good!)
I would like it to throw an error if there are multiple matches, though. Is there a way to do this?
count()
is a terminal operation so you can't do that. The stream can't be used after.Stream::size
?Stream
s so much more than I did before...LinkedHashSet
(assuming you want insertion order preserved) or aHashSet
all along. If your collection is only used to find a single user id, then why are you collecting all the other items? If there is a potential that you will always need to find some user id which also needs to be unique, then why use a list and not a set? You are programming backwards. Use the right collection for the job and save yourself this headache