1

In java, can you initialize a new map's keyset based on the values of an existing set?

Something like:

Set<String> setOfStrings = getSetFromSomeOtherFuntion();

Map<String, Boolean> map = new Hashmap<>(setOfStrings);

If that's possible, then I would presume the value for each entry in the map is null, which is ok, but even better would be if a default value could be set (for example, false if it's Boolean).

Inukshuk
  • 187
  • 2
  • 13

3 Answers3

7

You can use stream with Collectors.toMap like so:

Map<String, Boolean> map = setOfStrings.stream()
        .collect(Collectors.toMap(Function.identity(), v -> false));
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
7
Map<K, V> map = new HashMap<>();

setOfStrings.forEach(e -> map.put(e, false));
spongebob
  • 8,370
  • 15
  • 50
  • 83
0

If you have to do it in the constructor, you could do something like this:

Set<String> set = new HashSet<String>();
set.add("Key1");
set.add("Key2");
set.add("Key3");

Map<String, Boolean> map = new HashMap<String, Boolean>() {
    {
        set.forEach(str -> put(str, false));
    }
};

System.out.println(map);

Output:

{Key2=false, Key1=false, Key3=false}

However, this method is a little dirty and honestly unnecessary. You might want to see Efficiency of Java "Double Brace Initialization"?

Cardinal System
  • 2,749
  • 3
  • 21
  • 42