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.

1
  • 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
    Commented Jan 1, 2016 at 17:29

2 Answers 2

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);
}
8
  • 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
    Commented Jan 1, 2016 at 17:51
  • I guess that is already explained here. Use String instead of Integer for key. I have update that too. Commented Jan 1, 2016 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
    Commented Jan 1, 2016 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. Commented Jan 1, 2016 at 18:03
  • Ok Ok. Thank you. map.get(Key) this is that right?
    – Kiran
    Commented Jan 1, 2016 at 18:05
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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.