import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Main {
/**
*
* 关于map集合的遍历
*/
public static void main(String[] args) {
System.out.println("Hello World!");
// function01();
//function02();
//function03();
function04();
}
/**
*第一种遍历map集合的方法
* 通过map集合的keyset()方法来得到键的集合
*/
public static void function01(){
Map<Integer, String> map = new HashMap<>();
map.put(1,"一");
map.put(2,"二");
map.put(3,"三");
map.put(4,"四");
map.put(5,"五");
map.put(6,"六");
Set<Integer> set = map.keySet();
for(Integer in:set){
System.out.println(in+":"+map.get(in));
}
}
/**
* 第二种方法:通过map的entryset()
*/
public static void function02(){
Map map = new HashMap<Integer,String>();
map.put(1,"一");
map.put(2,"二");
map.put(3,"三");
map.put(4,"四");
map.put(5,"五");
map.put(6,"六");
Set<Map.Entry<Integer,String>> set = map.entrySet();
for(Map.Entry<Integer,String> entry:set){
System.out.println("key键为:"+entry.getKey()+"values为:"+entry.getValue());
}
}
/**
* 第三种方法:使用iterator
*/
public static void function03(){
Map map = new HashMap<Integer,String>();
map.put(1,"一");
map.put(2,"二");
map.put(3,"三");
map.put(4,"四");
map.put(5,"五");
map.put(6,"六");
Iterator<Map.Entry<Integer,String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<Integer, String> next =iterator.next();
System.out.println("key为:"+next.getKey()+"value为:"+next.getValue());
}
}
/**
* 第四种方法:使用map的values()方法:
*/
public static void function04(){
Map map = new HashMap<Integer,String>();
map.put(1,"一");
map.put(2,"二");
map.put(3,"三");
map.put(4,"四");
map.put(5,"五");
map.put(6,"六");
for (Object value : map.values()) {
System.out.println("value为:"+value);
}
;
}
}
关于map集合的遍历
最新推荐文章于 2020-04-04 18:53:00 发布