[英]Stream returns object only if first element of list is equal
I got simple data structure 我有简单的数据结构
private InMemoryDataBase() {
Account account1 = new Account("222", "222");
account1.getPlayers().add(new Player("john"));
account1.getPlayers().add(new Player("rachel"));
Account account2 = new Account("111", "111");
account2.getPlayers().add(new Player("max"));
accounts.add(account1);
accounts.add(account2);
}
public class Account {
private String accountNumber;
private String password;
private List<Player> players;
public Account(String accountNumber, String password){
this.accountNumber = accountNumber;
this.password = password;
players = new ArrayList<>();
}
}
And method that finds Account
if exists 找到Account
方法是否存在
private Optional<Account> findAccount() {
return dataBase.getAccounts()
.stream().findAny()
.filter(a -> a.getAccountNumber()
.equals(inputData.getAccountNumber()));
}
and then simple logic involved with this 然后是简单的逻辑
public void process() {
Optional<Account> account = findAccount();
if(account.isPresent()) {
if(validatePassword(account.get().getPassword())) {
outputData = new PlayersList(ConnectionInfo.Source.SERVER, inputData.getSourceID(), players);
} else {
outputData = new Message(ConnectionInfo.Source.SERVER, inputData.getSourceID(), "Incorrect password");
}
} else {
outputData = new Message(ConnectionInfo.Source.SERVER, inputData.getSourceID(), "Account not found");
}
}
Long story short, that's part of Client-Server communication, inputData
is data sent from Client application. 简而言之,这是Client-Server通信的一部分, inputData
是从客户端应用程序发送的数据。 And it seems to work, but only if I enter accountNumber equal to "222" (first one in InMemoryDataBase.accounts
. 它似乎工作,但只有当我输入accountNumber等于“222”( InMemoryDataBase.accounts
第一个)。
I'v did some testing, I can switch those values in my data base, I'll get positive result only if I request the first one in the list. 我做了一些测试,我可以在我的数据库中切换这些值,只有当我请求列表中的第一个时,我才会得到肯定的结果。 The other one ends up with message "Account not found". 另一个最终会收到“未找到帐户”的消息。
It seems like you should instead be doing 看起来你应该这样做
.filter(a -> a.getAccountNumber().equals(inputData.getAccountNumber()))
.findAny();
What you are currently ending up using is Optional.filter
which filters in the only Optional
you've got using findAny()
, based on the predicate if the value exists. 什么您目前结束了使用是Optional.filter
它过滤的唯一Optional
您使用得findAny()
如果该值存在,基于谓词。
Instead of which you should make use of Stream.filter
which filters in the stream of content and then you can use findAny()
over it to get the Optional
value. 而不是你应该使用在内容流中过滤的Stream.filter
,然后你可以使用findAny()
来获取Optional
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.