forEach
public static void fashion(Map<String, String> map) {
map.forEach((key, value) -> System.out.println("key = " + key + ", value = " + value));
}
keySet + forEach
public static void fashion(Map<String, String> map) {
Set<String> keySet = map.keySet();
keySet.forEach(key -> {
System.out.println("key = " + key + ", value = " + map.get(key));
});
}
keySet + for 循环
public static void fashion(Map<String, String> map) {
Set<String> keySet = map.keySet();
for (String key : keySet) {
System.out.println("key = " + key + ", value = " + map.get(key));
}
}
keySet + iterator
public static void fashion(Map<String, String> map) {
Set<String> keySet = map.keySet();
Iterator<String> iterator = keySet.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
System.out.println("key = " + next + ", value = " + map.get(next));
}
}
keySet + stream 流
public static void fashion(Map<String, String> map) {
map.keySet().stream().forEach(key -> {
System.out.println("key = " + key + ", value = " + map.get(key));
});
}
entrySet + forEach
public static void fashion5(Map<String, String> map) {
Set<Map.Entry<String, String>> entrySet = map.entrySet();
entrySet.forEach(entry -> {
System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
});
}
entrySet + for 循环
public static void fashion4(Map<String, String> map) {
Set<Map.Entry<String, String>> entrySet = map.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
}
}
entrySet + iterator
public static void fashion5(Map<String, String> map) {
Set<Map.Entry<String, String>> entrySet = map.entrySet();
Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> next = iterator.next();
System.out.println("key = " + next.getKey() + ", value = " + next.getValue());
}
}
entrySet + stream 流
public static void fashion7(Map<String, String> map) {
map.entrySet().stream().forEach(entry -> {
System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
});
}
Map#values 只能拿到所有 value
public static void fashion6(Map<String, String> map) {
Collection<String> values = map.values();
for (String value : values) {
System.out.println("value = " + value);
}
}