Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

 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. And it seems to work, but only if I enter accountNumber equal to "222" (first one in 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".

like image 672
user9309329 Avatar asked Sep 22 '18 19:09

user9309329


1 Answers

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.

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.

like image 178
Naman Avatar answered Oct 02 '22 22:10

Naman