Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList Retrieve object by Id

Tags:

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.

like image 700
Madhur Ahuja Avatar asked Nov 04 '13 18:11

Madhur Ahuja


People also ask

How do I retrieve an Object from an ArrayList?

An element can be retrieved from the ArrayList in Java by using the java. util. ArrayList. get() method.

How do I find an element in an ArrayList?

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.

How do you access an index from an ArrayList?

The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().


2 Answers

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.

like image 129
Amir Afghani Avatar answered Sep 23 '22 06:09

Amir Afghani


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 } 
like image 25
Ahamadullah Saikat Avatar answered Sep 23 '22 06:09

Ahamadullah Saikat