As we know, map is based on key-value pair associations, so interviewer can ask you this question if you are a beginner or having less than 3 years of experience.
So lets see how we can the key and values from a Map?
In Java we have and Map.Entry method that returns a collection-view of map.
So lets see how we can the key and values from a Map?
In Java we have and Map.Entry method that returns a collection-view of map.
Map< string string=""> map = new HashMap<>();
// Get keys and values
for (Map.Entry< string string=""> entry : map.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
System.out.println("Key: " + k + ", Value: " + v);
}
// In Java 8 we can use for each
map.forEach((k, v) -> {
System.out.println("Key: " + k + ", Value: " + v);
});
No comments:
Post a Comment