我正试图利用Java 8 Stream
s,以便找到
采用该守则:
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;
}
}
该代码基于其识别符号
将过滤线改为:
User match = users.stream().filter((user) -> user.getId() < 0).findAny().get();
扔下一个<代码>NoSuchElementException(正!)
不过,如果存在多种对应措施,我会错。 是否有办法这样做?