一、使用keySet()方法遍历HashMap值
通过keySet()方法可以获取HashMap中所有的键,然后可以通过遍历键的方式获取对应的值。具体步骤如下:
1.使用keySet()方法获取HashMap中所有的键,返回一个Set集合;
2遍历Set集合,依次获取每个键;
3.使用get()方法根据键获取对应的值。
示例代码如下:
HashMap<String, Integer> hashMap = new HashMap<>;//将键值对放入HashMap中
hashMap.put("apple",10);
hashMap.put("banana", 20);
hashMap.put("orange",30);//使用keySet()方法遍历HashMap
Set<String> keySet = hashMap.keySet();
for (String key : keySet) {
lnteger value = hashMap.get(key);
System.out.println(key + ": " + value);
}
结果
banana: 20
orange: 30
apple: 10
二、使用entrySet()方法遍历HashMap的值
通过entrySet()方法可以同时获取HashMap中的键和值,返回一个包含键值对的Set集合。具体步骤如下:
1.使用entrySet()方法获取HashMap中所有的键值对,返回一个包含键值对的Set集合;
⒉遍历Set集合,依次获取每个键值对的Entry对象;
3.使用getKey)方法获取Entry对象中的键,使用getValue()方法获取Entry对象中的值。
示例代码如下:
HashMap<String, Integer> hashMap = new HashMap<>();//将键值对放入HashMap中
hashMap.put("apple",10);
hashMap.put("banana",20);
hashMap.put("orange",30);
Set<Map.Entry<String, Integer>> entrySet = hashMap.entrySet();
for (Map.Entry<String, Integer> entry : entrySet) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key+"...."+value);
}
结果:
banana....20
orange....30
apple....10
三、使用values()方法遍历HashMap的值
通过values()方法可以获取HashMap中所有的值,返回一个Collection集合。具体步骤如下:
1.使用values)方法获取HashMap中所有的值,返回一个Collection集合;
2.遍历Collection集合,依次获取每个值。
示例代码如下:
HashMap<String, Integer> hashMap = new HashMap<>();//将键值对放入HashMap中
hashMap.put("apple",10);
hashMap.put("banana",20);
hashMap.put("orange",30);
//使用values()方法遍历HashMap的值
Collection<Integer> values = hashMap.values();
for (Integer value : values) {
System.out.println(value);
}
//使用keySet()方法遍历HashMap的键
Set<String> keySet = hashMap.keySet();
for (String key : keySet) {
System.out.println(key);
}
结果:
20
30
10
banana
orange
apple
四、使用forEach遍历HashMap的值
在Java 8及以上版本中,可以使用forEach方法遍历HashMap。具体步骤如下:
1.调用HashMap的forEach方法,并传入一个BiConsumer对象;
2.在BiConsumer的accept方法中,获取键和值,并进行相应的操作。
示例代码如下:
HashMap<String, Integer> hashMap = new HashMap<>();//将键值对放入HashMap中
hashMap.put("apple",10);
hashMap.put("banana",20);
hashMap.put("orange",30);
hashMap.forEach((key,value)->{
System.out.println(key+"*****"+value);
});
结果:
banana*****20
orange*****30
apple*****10
五、使用迭代器(iterator)方法遍历HashMap的值
具体步骤如下:
1.将map集合转为set集合
2.set集合利用iterator遍历set集合
HashMap<String, Integer> hashMap = new HashMap<>();//将键值对放入HashMap中
hashMap.put("apple",10);
hashMap.put("banana",20);
hashMap.put("orange",30);
Set<Map.Entry<String, Integer>> entrySet = hashMap.entrySet();
Iterator<Map.Entry<String, Integer>> iterator = entrySet.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
结果:
banana=20
orange=30
apple=10