0

I want my getLicense method to check if streamName value already exists in my HashMap streamMap, if not I generate a random hex and assign it to streamName in the HashMap. If it already exists I want to display from the HashMap the key for value streamName.

This is example hashmap:

{
    "2bd64e11d9b990eb4e02f7a1eebbd69e": "test68",
    "250d11594843674da1e3a742c12ba2b8": "test67",
    "dde270212efe372277d1abf57d393947": "test66"
}

This is method:

static HashMap<String, String> streamMap = new HashMap<String, String>();

@GetMapping("/getLicense")
@ResponseBody
public String addStream(@RequestParam("streamName") String streamName) {

    if(streamMap.containsValue(streamName)==false){
        String key = getRandomHexString();
        streamMap.put(key, streamName);
        streamService.addStream(new Stream(streamName, key));
        return key;
    }else{

 //here I would like for test67 return only m250d11594843674da1e3a742c12ba2b8

    }
}
Julia
  • 11
  • 5

1 Answers1

0

You can just use a simple for each loop to find the corresponding value to a key:

static HashMap<String, String> streamMap = new HashMap<String, String>();

@GetMapping("/getLicense")
@ResponseBody
public String addStream(@RequestParam("streamName") String streamName) {
    if(streamMap.containsValue(streamName)==false){
        String key = getRandomHexString();
        streamMap.put(key, streamName);
        streamService.addStream(new Stream(streamName, key));
        return key;
    }
    else{
        for (Entry<String, String> entry : streamMap.entrySet()) {
            if (entry.getValue().equals(streamName)) {
                return(entry.getKey());
            }
        }
    }
}
Aniketh Malyala
  • 2,650
  • 1
  • 5
  • 14
  • Thanks!! I saw this post but I chose the wrong way and I couldn't write a working method – Julia Aug 05 '21 at 09:56