Java Reference
In-Depth Information
// Use the forEach() method of the Map interface
map.forEach((String key, String value) -> {
System.out.println("key=" + key + ", value=" + value);
});
key=Donna, value=(205)678-9823
key=Ken, value=(205)678-9823
key=John, value=(342)113-9878
key=Richard, value=(245)890-9045
Listing 12-30 demonstrates how to get three different views of a Map and iterate over the elements in those views.
Listing 12-30. Using Keys, Values, and Entries Views of a Map
// MapViews.java
package com.jdojo.collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Collection;
public class MapViews {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("John", "(342)113-9878");
map.put("Richard", "(245)890-9045");
map.put("Donna", "(205)678-9823");
map.put("Ken", "(205)678-9823");
System.out.println("Map: " + map.toString());
// Print keys, values, and entries in the map
listKeys(map);
listValues(map);
listEntries(map);
}
public static void listKeys(Map<String,String> map) {
System.out.println("Key Set:");
Set<String> keys = map.keySet();
keys.forEach(System.out::println);
System.out.println();
}
public static void listValues(Map<String,String> map) {
System.out.println("Values Collection:");
Collection<String> values = map.values();
values.forEach(System.out::println);
System.out.println();
}
 
Search WWH ::




Custom Search