PSR
PSR

Reputation: 40358

How to search list of objects of java using a property name

I have a map like as follows

Map<String,Integer> map = new HashMap<String, Integer>();

map.put("one",1);
map.put("two",2);

If i want to get an element from map i can use

 map.get("one");

I have a list

List<TestVO> list = new ArrayList<TestVO>();
TestVO vo1 = new TestVO();
  vo1.setId(1);
  vo1.setName("one");


TestVO vo2 = new TestVO();
  vo2.setId(2);
  vo2.setName("two");

list.add(vo1);
 list.add(vo2);

If i want to search from this list which has name "one" i need to iterate this list.Is there any simple way to find out this?

I found this Searching in a ArrayList with custom objects for certain strings

But is there any other simple way to do that?Thanks in advance...

Upvotes: 0

Views: 1408

Answers (1)

Aniket Thakur
Aniket Thakur

Reputation: 69035

Searching data in Hash Map is of complexity O(1) where as in case of List it is O(N).

So unfortunately the answer is you have to iterate over the list. That is why choosing proper data structure is so important.

Upvotes: 3

Related Questions