samedi 2 mars 2019

Java: Returning a random value from a given key in a HashMap

I am trying to create a method which will return a random value from a list of strings in a hashmap when given a specific key. Here is my code below. (in particular look at the method "getRandomValue" as thats the one im having difficulty on). My question is: How do I look up a key in the map and return a random value from the hashmap?

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class Values {
    private Map<String, List<String>> map;
    private static Random rand = new Random();

public void ValueStore() {
    this.map = new HashMap<String, List<String>>();
}

public boolean containsKey(String key) {
    if(map.containsKey(key)) {
        return true;
    } return false;

}

public void put(String key, List<String> value) {
    map = new HashMap<>();
    map.put(key, value);

}

public String getRandomValue(String key) {
    for (String key1 : map.keySet()) {
        if(map.containsKey(key)) {
        //not sure what to do here  
        }
    }
    return key;

}

}




Aucun commentaire:

Enregistrer un commentaire