Reputation:
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.
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.
Upvotes: 0
Views: 89
Reputation: 1546
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);
}
}
}
Upvotes: 1