0
ACCOUNT p1= new SavingAccount("Saving","Ahmad",10000,3000,"43");
ACCOUNT p2= new CheckingAccount("Checking","Ali",20000,0 ,"0021");
ACCOUNT p3= new CheckingAccount("Checking","Mona",15000,0 ,"0033");
ArrayList  <ACCOUNT> ACCOUNTList = new ArrayList<ACCOUNT>();
    ACCOUNTList.add(p1);
    ACCOUNTList.add(p2);
    ACCOUNTList.add(p3);

I try to search a specific name on the list if it's on the list then print the object.

2 Answers2

1

How about using the Stream API.

Optional<Account> matchingAccount = accountList.stream().
                                                   filter(a -> a.getName().equals("someName")).
                                                   findFirst();

It will return an optional, as it's not guaranteed to find an account with any given name.

Marco Behler
  • 3,627
  • 2
  • 17
  • 19
0

You can use an "enhanced for loop", it will iterate over every element in the list without the need to set any conditions as in this case the purpose of this loop isn't complicated.

public ACCOUNT getACCByName(String name, ArrayList<ACCOUNT> list){

for(ACCOUNT acc : list){
    if(acc.getName().equals(name)){
      return acc;
        }
    }
return null;
}

But note for the future that as the list grows you might have multiple elements with the same name so make sure you search for something that can definitely be unique

v0lk
  • 58
  • 1
  • 6