0

I have an integer Array and a String, the string has characters P and N, I want to map the elements of the string with it's respective integer element. eg int array= 1,2,3,4,5 and string has PPNPN P->1,P->2,N->3,P->4,N->5.

https://ideone.com/vJldUJ

int array[]={1,2,3,4,5};
String s1="PPNPN";

String []array1=new String[s1.length()];

for(int i = 0; i < s1.length(); i++)
{
    array1[i] = String.valueOf(s1.charAt(i));
}
Map <String,Integer> map1=new HashMap<String,Integer>();

for(int i=0;i<array1.length;i++)
{
    map1.put(array1[i],array[i]);   
}

for (String key : map1.keySet()) 
{
    System.out.println(key + " " + map1.get(key));
}   

It is not printing all the values.

4
  • 1
    A map cannot have the same key multiple times. If you put an already existing key, it will only overwrite the existing value for that key . Commented Sep 19, 2018 at 6:44
  • Any other method besides mapping? Commented Sep 19, 2018 at 6:47
  • You may want to use a Map<String, List<Integer>> or similar in order to store a bunch of values with a single key Commented Sep 19, 2018 at 6:47
  • 1
    Please understand the behavior of Map interface first. Commented Sep 19, 2018 at 6:48

1 Answer 1

1

You can not use same key in HashMap. Adding new value to HashMap on already exist key will override the previous value. see I made a alternative solution for you https://ideone.com/PT6vvy.

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {

        int array[]={1,2,3,4,5};
        String s1="PPNPN";

        char []array1=s1.toCharArray();
        String out[] = new String[array1.length];
        for(int i = 0; i < array1.length; i++)
        {
            out[i] = array1[i]+" -> "+array[i];
        }


        for (String val : out) 
        {
            System.out.println(val);
        }   
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hey sir, Actually this was a part of my assessment, where P means positive and N means negative so I have to make all elements mapped with N negative and return the sum of values .
so, You need sum of all negative values ?
sum of both negative and positive numbers and return it.
Thanks sir, this pretty much sums my question :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.