I'm trying to convert the keys of a Map to Values of another Map, but finally only one key was return as Value. What was the problem? when the program excuted I got different Result
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class KeystoValues {
public static void KtoV(Map<Double, Integer> Key) {
Map<Double, Integer> List = new HashMap<Double, Integer>();
Map<Integer, Double> KeystoV = new HashMap<Integer, Double>();
System.out.println("List Map\n");
List.putAll(Key);
for(Map.Entry<Double, Integer> val : List.entrySet()) {
System.out.println(val.getKey() + "," + val.getValue());
}
for(int h = 1; h<=List.size(); h++)
for(Map.Entry<Double, Integer> convert : List.entrySet()) {
Double j = convert.getKey();
KeystoV.put(h, j);
}
System.out.println("\nSet of keys in List Map now converted to set "
+ "of Values and stored to KeystoV Map\n\nKeystoV Map\n");
for(Map.Entry<Integer, Double> converted : KeystoV.entrySet()) {
System.out.println(converted.getKey() + "," + converted.getValue());
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> Value = new ArrayList<Integer>();
Map<Double, Integer> Key = new HashMap<Double, Integer>();
Key.put(45.0,1);
Key.put(40.0,2);
Key.put(23.0,2);
Key.put(25.0,3);
Key.put(0.0,1);
KtoV(Key);
}
}
List Map
0.0,1
25.0,3
40.0,2
45.0,1
23.0,2
Set of keys in List Map now converted to set of Values and stored to KeystoV Map
KeystoV Map
1,23.0
2,23.0
3,23.0
4,23.0
5,23.0
The problem with your code is this nested for loop:
If you debug it, then you'll see that you are always putting the last iterated value of List.entrySet() as the value of all keys.
Try changing it to: