Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map.Entry interface in java

java.util.Map.Entry as I know is a public static interface in java.util package that returns collection view of a map but as far now I am confused with the static interface and as it is Map.Entry is it an inner interface if so how do we have inner static interfaces in java

like image 545
Ajay Avatar asked Sep 14 '11 12:09

Ajay


People also ask

Why entry interface is used in map?

Entry interface enables you to work with a map entry. The entrySet( ) method declared by the Map interface returns a Set containing the map entries. Each of these set elements is a Map. Entry object.

What is the difference between MAP and MAP entry?

The Map interface describes a data structure that stores key-value entries. The Map. Entry interface describes the structure of these entries, stores and provides a way of retrieving the associated key and value (dependent on implementation).

What is a mapping interface?

It models the mathematical function abstraction. The Map interface includes methods for basic operations (such as put , get , remove , containsKey , containsValue , size , and empty ), bulk operations (such as putAll and clear ), and collection views (such as keySet , entrySet , and values ).

Why do we use map in Java?

Maps are used for when you want to associate a key with a value and Lists are an ordered collection. Map is an interface in the Java Collection Framework and a HashMap is one implementation of the Map interface. HashMap are efficient for locating a value based on a key and inserting and deleting values based on a key.


2 Answers

The definition of Entry happens to live inside the definition of Map (allowed by java). Being static means you don't need an instance of Map to refer to an Entry.

It's easiest to show how to use Map.Entry by an example. Here's how you can iterate over a map

Map<Integer, String> map = new HashMap<Integer, String>();

for (Map.Entry<Integer, String> entry : map.entrySet()) {
    Integer key = entry.getKey();
    String value = entry.getValue();
    // do something with key and/or value etc
    // you may also alter the entry's value inside this loop via entry.setValue()
}
like image 69
Bohemian Avatar answered Sep 20 '22 02:09

Bohemian


There isn't really anything to be confused about.

Yes, Java allows interfaces to be members of classes or other interfaces.

No, that does not mean anything special. It changes absolutely nothing about how you can use such an interface or what you can do with it.

It only changes the name of that interface and creates a strong conceptual link between it and its enclosing type. In this case, a Map.Entry represents an entry of a Map. The designers of the API apparently felt that it made sense to stress this connection by making it a member type.

like image 20
Michael Borgwardt Avatar answered Sep 22 '22 02:09

Michael Borgwardt