✅ 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.