What is Map.Entry?

0118

Map.Entry is an inner interface in the Map interface in Java. It represents a key-value pair in a map. Each entry in a map consists of a key and its corresponding value. The Map.Entry interface provides methods to access the key and value of the entry.

Here are the key methods of the Map.Entry interface:

  • getKey(): Returns the key corresponding to this entry.
  • getValue(): Returns the value corresponding to this entry.
  • setValue(V value): Replaces the value corresponding to this entry with the specified value (optional operation).

You can use Map.Entry when you want to iterate over the entries of a map, for example:

Map<Integer, String> map = new HashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");

for (Map.Entry<Integer, String> entry : map.entrySet()) {
    System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}

This code snippet will print each key-value pair in the map.

0 Comments

no data
Be the first to share your comment!