java Map集合里面取键和值的四种方式
•
Jave
- 使用Map的keySet()方法获取键集合,再使用forEach循环遍历键集合,通过Map的get()方法获取对应的值。例如:
Map map = new HashMap();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
// 获取键集合,遍历键集合,通过get()方法获取对应的值
Set keySet = map.keySet();
for (String key : keySet) {
Integer value = map.get(key);
System.out.println("key:" + key + ",value:" + value);
}
- 使用Map的values()方法获取值集合,再使用forEach循环遍历值集合。例如:
Map map = new HashMap();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
// 获取值集合,遍历值集合
Collection values = map.values();
for (Integer value : values) {
System.out.println("value:" + value);
}
- 使用Map的entrySet()方法获取键值对集合,再使用forEach循环遍历键值对集合,通过Entry的getKey()方法获取键,通过Entry的getValue()方法获取值。例如:
Map map = new HashMap();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
// 获取键值对集合,遍历键值对集合,通过Entry的getKey()方法获取键,通过Entry的getValue()方法获取值
Set<Entry> entrySet = map.entrySet();
for (Entry entry : entrySet) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("key:" + key + ",value:" + value);
}
- 使用Java8的Stream流获取键值对集合,通过map方法获取键或值的流。例如:
Map map = new HashMap();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
// 获取键流,遍历键流
map.keySet().stream().forEach(key -> System.out.println("key:" + key));
// 获取值流,遍历值流
map.values().stream().forEach(value -> System.out.println("value:" + value));
// 获取键值对流,遍历键值对流,通过Entry的getKey()方法获取键,通过Entry的getValue()方法获取值
map.entrySet().stream().forEach(entry -> System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue()));
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/e9aa5a7665.html
