Simpler Java-8 solution involving Collectors.toMap:

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

An IllegalStateException will be thrown if duplicate key is encountered.

Answer from Tagir Valeev on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Map.Entry.html
Map.Entry (Java Platform SE 8 )
1 month ago - Replaces the value corresponding to this entry with the specified value (optional operation). (Writes through to the map.) The behavior of this call is undefined if the mapping has already been removed from the map (by the iterator's remove operation).
🌐
Baeldung
baeldung.com › home › java › java collections › java map › using the map.entry java class
Using the Map.Entry Java Class | Baeldung
January 8, 2024 - Here, the loop iterates over keySet. For each key, we get the corresponding value using Map.get. While this is an obvious way to use all of the entries in the map, it requires two operations for each entry — one to get the next key and one to look up the value with get.
Top answer
1 of 8
91

Simpler Java-8 solution involving Collectors.toMap:

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

An IllegalStateException will be thrown if duplicate key is encountered.

2 of 8
24

There is no inbuilt API in java for direct conversion between HashSet and HashMap, you need to iterate through set and using Entry fill in map.

one approach:

Map<Integer, String> map = new HashMap<Integer, String>();
    //fill in map
    Set<Entry<Integer, String>> set = map.entrySet();

    Map<Integer, String> mapFromSet = new HashMap<Integer, String>();
    for(Entry<Integer, String> entry : set)
    {
        mapFromSet.put(entry.getKey(), entry.getValue());
    }

Though what is the purpose here, if you do any changes in Set that will also reflect in Map as set returned by Map.entrySet is backup by Map. See javadoc below:

Set<Entry<Integer, String>> java.util.Map.entrySet()

Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

🌐
Tutorialspoint
tutorialspoint.com › java › java_mapentry_interface.htm
Java - The Map.Entry Interface
Home Whiteboard Practice Code Graphing Calculator Online Compilers Articles Tools ... Python TechnologiesDatabasesComputer ProgrammingWeb DevelopmentJava TechnologiesComputer ScienceMobile DevelopmentBig Data & AnalyticsMicrosoft TechnologiesDevOpsLatest TechnologiesMachine LearningDigital MarketingSoftware QualityManagement Tutorials View All Categories ... Java Vs. C++ ... The Map.Entry interface enables you to work with a map entry.
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › util › Map.Entry.html
Map.Entry (Java Platform SE 7 )
These Map.Entry objects are valid only for the duration of the iteration; more formally, the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry. ... Returns the key corresponding to this entry.
🌐
Java
download.java.net › java › early_access › panama › docs › api › java.base › java › util › Map.Entry.html
Map.Entry (Java SE 19 & JDK 19 [build 1])
Replaces the value corresponding to this entry with the specified value (optional operation). (Writes through to the map.) The behavior of this call is undefined if the mapping has already been removed from the map (by the iterator's remove operation).
Top answer
1 of 6
12

I have searched on the Map interface methods but there is no method that takes an entry and puts it in the map. Therefore I have implemented it by myself using a little bit of inheritance and Java 8 interfaces.

import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Maps {

    // Test method
    public static void main(String[] args) {
        Map.Entry<String, String> entry1 = newEntry("Key1", "Value1");
        Map.Entry<String, String> entry2 = newEntry("Key2", "Value2");

        System.out.println("HashMap");
        MyMap<String, String> hashMap = new MyHashMap<>();
        hashMap.put(entry1);
        hashMap.put(entry2);

        for (String key : hashMap.keySet()) {
            System.out.println(key + " = " + hashMap.get(key));
        }

        System.out.println("\nTreeMap");
        MyMap<String, String> treeMap = new MyTreeMap<>();
        treeMap.put(entry1);
        treeMap.put(entry2);


        for (String key : treeMap.keySet()) {
            System.out.println(key + " = " + treeMap.get(key));
        }
    }


    /**
     * Creates a new Entry object given a key-value pair.
     * This is just a helper method for concisely creating a new Entry.
     * @param key   key of the entry
     * @param value value of the entry
     * 
     * @return  the Entry object containing the given key-value pair
     */
    private static <K,V> Map.Entry<K,V> newEntry(K key, V value) {
        return new AbstractMap.SimpleEntry<>(key, value);
    }

    /**
     * An enhanced Map interface.
     */
    public static interface MyMap<K,V> extends Map<K,V> {

        /**
         * Puts a whole entry containing a key-value pair to the map.
         * @param entry 
         */
        public default V put(Entry<K,V> entry) {
            return put(entry.getKey(), entry.getValue());
        }
    }

    /**
     * An enhanced HashMap class.
     */
    public static class MyHashMap<K,V> extends HashMap<K,V> implements MyMap<K,V> {}

    /**
     * An enhanced TreeMap class.
     */
    public static class MyTreeMap<K,V> extends TreeMap<K,V> implements MyMap<K,V> {}
}

The MyMap interface is just an interface that extends the Map interface by adding one more method, the public default V put(Entry<K,V> entry). Apart from just defining the method, a default implementation is coded too. Doing that, we can now add this method to any class that implements the Map interface just by defining a new class that implements the MyMap interface and extending the map implementation class of our choice. All of that in one line! This is demonstrated in the bottom of the code above where two classes are created each extending the HashMap and the TreeMap implementations.

2 of 6
7

To instantiate a Map with Entries (in the same way as you can do Arrays.asList(T... a) or Sets.newHashSet(T... a) in Google Guava library, I found this:

import java.util.AbstractMap;
import java.util.Map;

public class MapWithEntries {

    private static final Map.Entry<String, String> ENTRY_1 = new AbstractMap.SimpleEntry<>("A", "Hello");
    private static final Map.Entry<String, String> ENTRY_2 = new AbstractMap.SimpleEntry<>("B", "World");

    private static final Map<String, String> MAP_WITH_ENTRIES = Map.ofEntries(ENTRY_1, ENTRY_2);
}
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Map › entries
Map.prototype.entries() - JavaScript - MDN Web Docs
July 20, 2025 - const myMap = new Map(); myMap.set("0", "foo"); myMap.set(1, "bar"); myMap.set({}, "baz"); const mapIter = myMap.entries(); console.log(mapIter.next().value); // ["0", "foo"] console.log(mapIter.next().value); // [1, "bar"] console.log(mapIter.next().value); // [Object, "baz"]
🌐
Oracle
docs.oracle.com › javase › 9 › docs › api › java › util › Map.Entry.html
Map.Entry (Java SE 9 & JDK 9 )
Replaces the value corresponding to this entry with the specified value (optional operation). (Writes through to the map.) The behavior of this call is undefined if the mapping has already been removed from the map (by the iterator's remove operation).
Find elsewhere
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › docs › api › java.base › java › util › Map.Entry.html
Map.Entry (Java SE 17 & JDK 17)
January 20, 2026 - Replaces the value corresponding to this entry with the specified value (optional operation). (Writes through to the map.) The behavior of this call is undefined if the mapping has already been removed from the map (by the iterator's remove operation).
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › util › Map.Entry.html
Map.Entry (Java SE 11 & JDK 11 )
January 20, 2026 - Replaces the value corresponding to this entry with the specified value (optional operation). (Writes through to the map.) The behavior of this call is undefined if the mapping has already been removed from the map (by the iterator's remove operation).
🌐
Tabnine
tabnine.com › home page › code › java › java.util.map$entry
Java Examples & Tutorials of Map$Entry.getValue (java.util) | Tabnine
public Map<String, Double> getOperatorHashCollisionsAverages() { return operatorHashCollisionsStats.entrySet().stream() .collect(toMap( Map.Entry::getKey, entry -> entry.getValue().getWeightedHashCollisions() / operatorInputStats.get(entry.getKey()).getInputPositions())); }
🌐
BeginnersBook
beginnersbook.com › 2014 › 06 › map-entry-interface-in-java
Map.Entry Interface in Java
September 11, 2022 - Map.Entry interface helps us iterating a Map class such as HashMap, TreeMap etc. In this tutorial, we will learn methods and usage of Map.Entry interface in Java. 1) boolean equals(Object o): Compares the specified object with this entry for equality. 2) Key getKey(): Returns the key corresponding to this entry.
🌐
Oracle
docs.oracle.com › javase › 6 › docs › api › java › util › Map.Entry.html
Map.Entry (Java Platform SE 6)
These Map.Entry objects are valid only for the duration of the iteration; more formally, the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry. ... Returns the key corresponding to this entry.
🌐
Quora
quora.com › In-Java-what-is-Map-Entry-and-how-to-use-it
In Java, what is Map.Entry and how to use it? - Quora
Answer (1 of 3): [code ]Map.Entry[/code] interface in Java provides certain methods to access the entry in the Map. By gaining access to the entry of the Map we can easily manipulate them. [code ]Map.Entry[/code] is a generic and is defined in the[code ] java.util [/code]package. Some of the met...
🌐
Java
download.java.net › java › early_access › valhalla › docs › api › java.base › java › util › Map.Entry.html
Map.Entry (Java SE 23 & JDK 23 [build 1])
This connection to the backing map is valid only during iteration of the entry-set view. During the iteration, if supported by the backing map, a change to an Entry's value via the setValue method will be visible in the backing map. The behavior of such an Entry is undefined outside of iteration of the map's entry-set view.
🌐
Coderanch
coderanch.com › t › 755986 › java › Create-Map-existing-List-Entry
Create a Map out of existing List of Entry (Java in General forum at Coderanch)
November 28, 2022 - Not sure how this can be done as I am new to this forum and I just pasted my code from my Eclipse and then put it under Code. And finally added problem description. Anyway, here is what I have: List<Map.Entry<String, String>> Eg: 'One', 'Sunday' 'One', 'Monday' 'One', 'Tuesday' 'Two', 'Wednesday' 'Two', 'Thursday' 'Three', 'Friday' And here is what I want: Map<String, List<String>> Eg: 'One' -> 'Sunday', 'Monday', 'Tuesday' 'Two' -> 'Wednesday', 'Thursday' 'Three' -> 'Friday' Hope the above helps
🌐
Bureau of Economic Geology
beg.utexas.edu › lmod › agi.servlet › doc › detail › java › util › Map.Entry.html
: Interface Map.Entry
Replaces the value corresponding to this entry with the specified value (optional operation). (Writes through to the map.) The behavior of this call is undefined if the mapping has already been removed from the map (by the iterator's remove operation).
🌐
Baeldung
baeldung.com › home › java › java collections › java map › initialize a hashmap in java
Initialize a HashMap in Java | Baeldung
September 7, 2024 - Map<String, Integer> map = Stream.of(new Object[][] { { "data1", 1 }, { "data2", 2 }, }).collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1])); As a result, we create a map of the key as a String and value as an Integer. Here we’ll use the instances of Map.Entry.