How can I print an amount of random vehicle in vec? For instance if the n is 2, then print bus = 16.
class T {
Map<String, Integer> vec = new HashMap<String, Integer>();
List<String> transp = Arrays.asList("Car", "Bus", "Train");
List<Integer> amount = Arrays.asList(58, 16, 33);
int val() {
for (int i = 0; i < vec.size(); i++)
vec.put(transp.get(i), amount.get(i));
System.out.println(vec);
Random rand = new Random();
int n = 0 + rand.nextInt(vec.size());
}
}
Thanks!
Given that you’ve already got the key/value pairs as separate lists, why not just use:
If you have to do it via the map, you could use:
It’s not really a good way of doing things – maps are meant for looking things up by key, not for getting entries by index, given that they’re inherently unordered.