0

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...

Community
  • 1
  • 1
PSR
  • 39,804
  • 41
  • 111
  • 151
  • have you tried using `Collections.binarySearch(list, "one");`? – Linus Nov 22 '13 at 06:56
  • @Linus "one" is a name property of TestVO class. Instances of TestVO are stored in the List. – Aniket Thakur Nov 22 '13 at 06:57
  • Did you read [this answer](http://stackoverflow.com/a/12496479/2024761) in the question you linked? – Rahul Nov 22 '13 at 06:58
  • @R.J I saw the marked answer – PSR Nov 22 '13 at 06:59
  • Marked answer doesn't mean that's the best answer. It means that the marked answer helped OP solve their problem, but doesn't mean other answers are wrong. If you'd read the other answers, you'd have seen it and if you're not bound by any clause to not use a 3rd-party lib, then the answer I proposed could very well be your solution. Why not give it a try? – Rahul Nov 22 '13 at 07:01
  • In my first comment, I linked that answer. "this answer" in my first comment, is a link. – Rahul Nov 22 '13 at 07:06

1 Answers1

3

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.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • @Debriter I meant HashMap if that is what your point is. Refer - http://stackoverflow.com/questions/4553624/hashmap-get-put-complexity – Aniket Thakur Feb 04 '15 at 14:21