ArrayList Retrieve object by Id
Java Solution:
Account account = accountList.stream().filter(a -> a.getId() == YOUR_ID).collect(Collectors.toList()).get(0);
Kotlin Solution 1:
val index = accountList.indexOfFirst { it.id == YOUR_ID }
val account = accountList[index]
Kotlin Solution 2:
val account = accountList.first { it.id == YOUR_ID }
Assuming that it is an unordered list, you will need to iterate over the list and check each object.
for(int i = 0; i < sizeOfList; i++) {
list.get(i).equals(/* What you compare against */)
}
There's also the other for
syntax:
for(Account a : accountList)
You could put this loop into a helper method that takes an Account
and compares it against each item.
For ordered lists, you have more efficient search options, but you will need to implement a search no matter what.
It sounds like what you really want to use is a Map
, which allows you to retrieve values based on a key. If you stick to ArrayList
, your only option is to iterate through the whole list and search for the object.
Something like:
for(Account account : accountsList) {
if(account.getId().equals(someId) {
//found it!
}
}
versus
accountsMap.get(someId)
This sort of operation is O(1)
in a Map
, vs O(n)
in a List
.
I was thinking of extending ArrayList but I am sure there must be better way.
Generally speaking, this is poor design. Read Effective Java Item 16 for a better understanding as to why - or check out this article.
A better way to do this would be to use a Map.
In your case, you could implement it in the following way
Map<account.getId(), account>
you can use the "get" method to retrieve the appropriate account object.
accountMap.get(id);