Java.Collections.Make a HashMap from a HashSet>.

✅ If the HashSet comes from an existing Map.entrySet():

Map<K, V> map = new HashMap<>(Map.ofEntries(...)); // Java 9+

But more generally, if you already have a Set<Map.Entry<K, V>> (like a HashSet), here’s the clear and compatible way:


✅ One-liner using a loop (Java 8+):

Map<K, V> map = new HashMap<>();
entrySet.forEach(e -> map.put(e.getKey(), e.getValue()));

Or as a stream one-liner (Java 8+):

Map<K, V> map = entrySet.stream()
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

💡 Example:

Set<Map.Entry<String, Integer>> entrySet = new HashSet<>();
entrySet.add(new AbstractMap.SimpleEntry<>("apple", 1));
entrySet.add(new AbstractMap.SimpleEntry<>("banana", 2));

Map<String, Integer> map = entrySet.stream()
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

System.out.println(map); // Output: {apple=1, banana=2}

🧠 TL;DR

ApproachCode snippet
Loop-basedentrySet.forEach(e -> map.put(...))
Stream-based (1-liner)entrySet.stream().collect(...)
This entry was posted in Без рубрики. Bookmark the permalink.