0

Suppose I have LinkedhashMap<String, List> myLHM = new LinkedHashMap<>()

Values of myLHM :

<Roy,[1,2,3]>
<Roy,[14,15,16]>
<Neha,[1,5,6]>
<Neha,[11,12,13]>
<Jane,[11,8,9]>

In above eg., Roy and Neha is repetitive/duplicate.

Is it possible to hold duplicate keys in myLHM ? Because I'm not able to store duplicate keys

No? Then what is the alternative to LinkedHashMap to hold duplicate keys?

TIA!

Edit: Those two Roy and Neha are each the same person

3 Answers3

2

I don't know of any map in the standard java library that can hold duplicate keys, but Guava is an excellent extension to the normal java Collections (and more) done by Google. There you have Multimap which can hold several values for the same key (I guess this is what you want in the end). The main benefit I find in using such a library/implementation is that it will take care of everything for you associated with the storage of the values and you don't need to bother about implementing it yourself.

PS: Guava is not just about Collections, which I think it's another Pro why you should check it out.

Fred
  • 16,367
  • 6
  • 50
  • 65
1

Add a List of items by key. Whenever you insert, if key was found, just add to the collection. When not found, add a new colelction with current item.

eduyayo
  • 2,020
  • 2
  • 15
  • 35
1

I solved this by myself.

What I did is used :

LinkedHashMap<String, ArrayList<ArrayList>> myLHM = new LinkedHashMap<>() ;

Inserted into it as:

ArrayList<ArrayList> multiDimArray = new ArrayList<>();

ArrayList list = new ArrayList();
list.add("abc");//some string 1
list.add("lmn");//some string 2
list.add("xyz");//some string 3

multiDimArray.add(list);
myLHM.put("abc"/*use your variable OR pass value like myList.get(position)*/,multiDimArray);

Fetched / Retrieved values as:

List tempNames=new ArrayList();
Iterator myVeryOwnIterator = myLHM.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
     tempNames.add(myVeryOwnIterator.next());
}

ArrayList<ArrayList> tempArrayList = new ArrayList();
for (int i=0;i<tempNames.size();i++){
    tempArrayList.addAll(myLHM.get(tempNames.get(i)));
}

String item = null; int year = 0; int amount = 0; 
for (int i=0;i<tempArrayList.size();i++) {
    for (int j=0;j<tempArrayList.get(i).size();j++){
        if(j==0){
           item = (String) tempArrayList.get(i).get(j);
           item = item.replaceAll("\\s", "_");
           } else if (j==1){
           year = Integer.valueOf(tempArrayList.get(i).get(j).toString());
           } else if (j==2){
           amount = Integer.valueOf(tempArrayList.get(i).get(j).toString());
           } else {
           Log.e("Problem","for loop error");
           }
    }
    db.execSQL("INSERT INTO ch // my insert query...
    VALUES(" +"'" + item +"'," + year +"," + amount +"," + id +");");
}