0

I want to Put two arrays value in LinkedHashMap as key-value. Here is the snippet that I'm using:

        String[] s = answer.split("\\,");  
        String[] ss = aa.split("\\,");
        System.out.println(ss.length);  -->prints 3 
        System.out.println(s.length);   -->prints 3

What I want is to put s values as Key and ss values as Value in HashMap.

I'm trying to write code.

    for(int i=0;i<s.length;i++){
            for(int j= 0;j<ss.length;j++){
                if(s[i].length()==s[j].length()){
                    testMap.put(s[i], ss[j]);
                }
            }
        }

But unable to Put into Map. What I've done wrong? And I'm using LinkedHashMap to preserve the order of Insertion.

  • I do not see where you are trying to perform addition in your code example... what are you trying to add? – Yoshiya Aug 31 '16 at 17:46
  • What is the error or what are the values you have in your arrays? – Rishal Aug 31 '16 at 17:47
  • Are you sure you want to add the same array elements as key- value pair. `testMap.put(s[i], s[j])` it will add `s[i]` element as key and value. What is the output you are getting and what you are unable to add? – Rishal Aug 31 '16 at 17:50
  • @Rishaldevsingh corrected the code. – Manoj Kumar Giri Aug 31 '16 at 17:51
  • Here is output. And I know what is happening. It is putting last value of ss array in each keys. How to separate them? Key = ID Key = NAME Key = VALUES Values= ROMEO Values= ROMEO Values= ROMEO – Manoj Kumar Giri Aug 31 '16 at 17:52
  • post your `answer` and `aa` strings as well. – Rishal Aug 31 '16 at 17:55
  • @Rishaldevsingh Output of aa String : 1 KLAXXON ROMEO and output is :Key = ID Key = NAME Key = VALUES Values= ROMEO Values= ROMEO Values= ROMEO – Manoj Kumar Giri Aug 31 '16 at 17:57
  • Assuming your Strings are `String answer="ID,NAME,VALUES"; String aa="1,KLAXXON,ROMEO";` you are trying to map `ID` with `1` ,`NAME` with `KLAXXON` and `VALUES` with `ROMEO` ryt? if yes then why you are using two loops. – Rishal Aug 31 '16 at 18:04
  • @Rishaldevsingh Yes that is what I'm trying to do. And how can I do it? I know using two loops is not gonna help and it keeps adding the last value in each keys. – Manoj Kumar Giri Aug 31 '16 at 18:09

2 Answers2

0

Here is the solution:

        for(int i=0;i<s.length;i++){
                testMap.put(s[i], ss[i]);
        }

I just have to change my loop condition to this. Instead of using two for loops. Thanks everybody.

0

Use this code, It will add accordingly

String answer = "ID,NAME,VALUES"; String aa = "1,KLAXXON,ROMEO"; String[] s = answer.split("\\,"); String[] ss = aa.split("\\,");

for (int i = 0; i < s.length; i++) { testMap.put(s[i], ss[i]); }

Output: {ID=1, NAME=KLAXXON, VALUES=ROMEO}

Rishal
  • 1,480
  • 1
  • 11
  • 19