0

I'm trying to create a list that contains a value and a key, but I want the value to stay the same, and just have multiple keys. So this is just an example:

        Map<String, Integer> map = new HashMap<>();
        String str = "hey";
        for(int i = 0; i < 20; i ++){
             map.put(str, i);
        }

This is just an example. But how would I go about adding the same string and a different key? Do I need to not use HashMap or it is do-able with it? (because HashMap is not necessary for me, as long as it stores 2 values it's good for me)

Destinations
  • 11
  • 1
  • 5
  • key should be unique – Malavan Oct 25 '19 at 10:30
  • You want i to be constanst or str? – Prasad Oct 25 '19 at 10:33
  • Key is unique, I'm assigning it to a different "i" everytime, but it just overwrites the previous set with a new key. – Destinations Oct 25 '19 at 10:34
  • 2
    @Destinations no, you're putting `str` as the key. It's `put(key, value)`. – Kayaman Oct 25 '19 at 10:35
  • Looks like you have hard coded the key, which does not really fit to your description. Maybe take a `Map` and change the `for` loop to do `map.put(i, str);`? I think filling up a map with several different keys that all have the same value associated is not the way a `Map` should be used, but it will work, of course. – deHaar Oct 25 '19 at 10:35
  • Map> map = new HashMap<>(); if(map.get(key) != null then List ints = map.get(key); ints.add(key); else map.put(key, i); – Prasad Oct 25 '19 at 10:35
  • 1
    omg @Kayaman , I feel like an idiot, problem fixed, thanks. – Destinations Oct 25 '19 at 10:37

1 Answers1

0

You can use a Map with a List or Set Value

Map<String, Set<Integer>> map = new HashMap<>();
String str = "hey";
for(int i = 0; i < 20; i ++){
 if(map.get(str) == null)  map.put(str, new HashSet<>());
 map.get(str).add(i);
}

octopus
  • 319
  • 1
  • 4
  • 16