Suppose I have an ArrayList<Account>
of my custom Objects which is very simple. For example:
class Account { public String Name; public Integer Id; }
I want to retrieve the particular Account
object based on an Id
parameter in many parts of my application. What would be best way of going about this ?
I was thinking of extending ArrayList
but I am sure there must be better way.
An element can be retrieved from the ArrayList in Java by using the java. util. ArrayList. get() method.
ArrayList. contains() method can be used to check if an element exists in an ArrayList or not. This method has a single parameter i.e. the element whose presence in the ArrayList is tested. Also it returns true if the element is present in the ArrayList and false if the element is not present.
The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With