I want map integer to vector in java…
for example in c++ we use → map< int, vector > can we do this in java if Yes… then How?
I want map integer to vector in java…
for example in c++ we use → map< int, vector > can we do this in java if Yes… then How?
import java.util.*;
public class Main
{
public static void main(String[] args) {
Map<Integer, Vector<Integer>> my_map = new HashMap<>();
my_map.put(1, new Vector<Integer>());
my_map.get(1).add(1);
my_map.get(1).add(2);
// Nullpointer exception
// my_map.get(2).add(1);
System.out.println(my_map);
my_map.put(2, new Vector<Integer>());
my_map.get(2).add(5);
System.out.println(my_map);
}
}
Output
{1=[1, 2]}
{1=[1, 2], 2=[5]}
You can also use loops to insert, but make sure the key is present.
thank You so much for your help
You can do something like this
Map<Integer,ArrayList<Integer>> mp = new HashMap<>();
for(int i=0; i<n; i++){
if(!mp.containsKey(i)){
mp.put(i, new ArrayList<Integer>());
}
mp.get(i).add(i);
}
I hope it helps