Search code examples
javaarraylistmultidimensional-arrayguavamaplist

Java MultipMap single key with multiple value


I working on java application and this is very basic test tool. What we need to do is we have to store multiple value with single key in map list, for example 'key,value,value' that is '1,www.google.com,test', '2,www.gmail.com,Test' and so on. Also, we need to modify value (test) for respective key once the process is completed.

Is there any way of doing this, I have search on Google and could not find it working properly 'https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.1/org/apache/commons/collections/MultiMap.html'

I would appreciate if you can give me example code with your valued answer.

Code:

import org.apache.commons.collections.map.MultiKeyMap;

public class test {

static MultiKeyMap masterLinkList = new MultiKeyMap();
static String fetchUrl, urlStatus, urlMessage;

public static void main(String[] args) {
    // TODO Auto-generated method stub

    masterLinkList.put(1,"www.google.com", "Test");
    masterLinkList.put(2,"www.gmail.com", "Test");

    System.out.println(masterLinkList.get(1));

    masterLinkList.put(2,"www.gmail.com", "Test");

    if(masterLinkList.containsKey(1)&&masterLinkList.containsValue("Test")){
        masterLinkList.put(1,"www.gmail.com", "Passed");
    }
    System.out.println(masterLinkList.get(1));
}

}

Thanks,


Solution

  • You can use java core classes:

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class MultiMap {
        public static void main(String[] args) {
            final Map<String, List<String>> map = new HashMap<String, List<String>>();
    
            final List<String> valSetOne = new ArrayList<String>();
            valSetOne.add("www.google.com");
            valSetOne.add("test");
    
            final List<String> valSetTwo = new ArrayList<String>();
            valSetTwo.add("www.gmail.com");
            valSetTwo.add("Test");
    
            map.put("1", valSetOne);
            map.put("2", valSetTwo);
    
            final List<String> values = map.get("1");
            System.out.println("Before changing: " + values.get(1));
            values.set(1, "newTest");
            System.out.println("After changing: " + values.get(1));
        }
    }
    

    How wrote below, you can use Google Guava Collections or Apache Commons Collection too. For example, look link: http://java.dzone.com/articles/hashmap-%E2%80%93-single-key-and