0

I have a ArrayList as shown below:

Id1, value1
Id1, value2
Id2, value1
Id2, value2
Id2, value3
Id3, value1
Id3, value2
Id3, value3
Id3, value4
Id3, value5 

etc...

In a class I have id value. I have to fetch the values corresponding to an id value. For example If I give id1 then I need value1 and value2. Which collection mechanism should I use to achieve my objective. I am a beginner please do suggest me. Thanks in advance. All suggestions are welcome.

Kiran
  • 96
  • 2
  • 10
  • Ok I will use HashMap for collection. Later which method of HaspMap will be useful so that when I give an Id value I should get corresponding value from collection. – Kiran Jan 01 '16 at 17:29

2 Answers2

1

Assuming the Keys are type of String and values are of type String. You can use a Map<String, List<String>>.

For each id store the values in a List, so when you look for a id you can retrieve all the values.

Here is the code snippet, which first checks the keys is already present, if not, then creates new empty list. The values are added to the list and put into the map. You can use the get(Key) api for retrieving the values from map.

public void add(String key, String value) {
  List<String> values = map.get(key);
  if (values == null) {
    values = new ArrayList<String>();
  }
  values.add(value);
  map.put(key, values);
}
YoungHobbit
  • 13,254
  • 9
  • 50
  • 73
  • Thanks for quick reply, My Id is String value, I will have the array list. I have to pass id to a method and I have to get list of values containing that key. Can you please explain how it can be done? – Kiran Jan 01 '16 at 17:51
  • I guess that is already explained here. Use `String` instead of `Integer` for key. I have update that too. – YoungHobbit Jan 01 '16 at 17:56
  • In the add method we are adding the values to the list right? will we get the values pertaining to a key value in the same method. Please correct me If I am wrong. I did not understand String parameter in the add method. – Kiran Jan 01 '16 at 18:00
  • Yes, It is adding values to the list. For getting the values back you can use the `get(Key)` from the map api. – YoungHobbit Jan 01 '16 at 18:03
  • Ok Ok. Thank you. map.get(Key) this is that right? – Kiran Jan 01 '16 at 18:05
  • Yes. That is right. Please read [HashMap.get(Object)](http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#get%28java.lang.Object%29). – YoungHobbit Jan 01 '16 at 18:06
  • Ok thanks a lot for your help. If I get any doubt while implementing I will contact you. Please guide me. – Kiran Jan 01 '16 at 18:09
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/99476/discussion-between-younghobbit-and-kiran). – YoungHobbit Jan 01 '16 at 18:11
1

Consider Guava's MultiMap: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html

Guava is a library from Google, that provides a lot of useful utilities, commonly needed in Java.

Dima
  • 39,570
  • 6
  • 44
  • 70