- 使用Map的keySet()方法獲取鍵集合,再使用forEach循環(huán)遍歷鍵集合,通過Map的get()方法獲取對應(yīng)的值。例如:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
// 獲取鍵集合,遍歷鍵集合,通過get()方法獲取對應(yīng)的值
Set<String> keySet = map.keySet();
for (String key : keySet) {
Integer value = map.get(key);
System.out.println("key:" + key + ",value:" + value);
}
- 使用Map的values()方法獲取值集合,再使用forEach循環(huán)遍歷值集合。例如:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
// 獲取值集合,遍歷值集合
Collection<Integer> values = map.values();
for (Integer value : values) {
System.out.println("value:" + value);
}
- 使用Map的entrySet()方法獲取鍵值對集合,再使用forEach循環(huán)遍歷鍵值對集合,通過Entry的getKey()方法獲取鍵,通過Entry的getValue()方法獲取值。例如:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
// 獲取鍵值對集合,遍歷鍵值對集合,通過Entry的getKey()方法獲取鍵,通過Entry的getValue()方法獲取值
Set<Entry<String, Integer>> entrySet = map.entrySet();
for (Entry<String, Integer> entry : entrySet) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("key:" + key + ",value:" + value);
}
- 使用Java8的Stream流獲取鍵值對集合,通過map方法獲取鍵或值的流。例如:
Map<String, Integer> 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()));
文章來源地址http://www.zghlxwxcb.cn/news/detail-791808.html
文章來源:http://www.zghlxwxcb.cn/news/detail-791808.html
到了這里,關(guān)于java Map集合里面取鍵和值的四種方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!