Java.Collections.If you want to create a HashSet from the keys of a HashMap, it’s super simple — just grab the key set and pass it to the HashSet constructor.

✅ One-liner:

Set<KeyType> keySet = new HashSet<>(map.keySet());

💡 Example:

Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("cherry", 3);

Set<String> keySet = new HashSet<>(map.keySet()); // One-liner

System.out.println(keySet); // Output: [banana, cherry, apple]

🧠 Notes:

  • map.keySet() returns a live view of the map’s keys.
  • Wrapping it in a HashSet gives you a separate copy.
  • If you only want a read-only view, you could use map.keySet() directly.
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.