一.遍历HashMap
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
//HashMap的几种遍历方式
public class Text2 {
public static void main(String[] args) {
HashMap hashmap=new HashMap();
hashmap.put("赵二", 98);
hashmap.put("钱三", 80);
hashmap.put("孙四", 91);
hashmap.put("李五", 76);
method1(hashmap);
method2(hashmap);
method3(hashmap);
method4(hashmap);
}
//方法1:最常用的一种遍历方法,先取key值再取value值
private static void method1(HashMap hashmap){
System.out.println("方法1:");
for(String i:hashmap.keySet()){
System.out.println(i+":"+hashmap.get(i));
}
System.out.println();
}
//方法2-1:通过Map.entrySet使用iterator遍历key和value
private static void method2(HashMap hashmap) {
System.out.println("方法2-1:");
for (Iterator> it=hashmap.entrySet().iterator();it.hasNext();) {
Map.Entry entry=it.next();
System.out.println(entry.getKey()+":"+entry.getValue());
}
System.out.println();
}
//方法2-2:非迭代器的增强for循环形式遍历key和value
private static void method3(HashMap hashmap) {
System.out.println("方法2-2:");
for(Map.Entry entry:hashmap.entrySet()){
System.out.println(entry.getKey()+":"+entry.getValue());
}
System.out.println();
}
//只遍历values而不遍历key
private static void method4(HashMap hashmap) {
System.out.println("方法4:");
for(int sore:hashmap.values()){
System.out.println(":"+sore);
}
System.out.println();
}
}
二.遍历HashSet
import java.util.HashSet;
import java.util.Iterator;
/*
HashSet的几种遍历方式
HashSet默认无重复、无序添加的集合,若要有序则用TreeSet,若要要按照添加的顺序存放则用LinedHashSet
* */
public class Text2 {
public static void main(String[] args) {
//默认是按照顺序输出
HashSet hashset=new HashSet();
hashset.add(5);
hashset.add(4);
hashset.add(8);
hashset.add(1);
hashset.add(2);
method1(hashset);
method2(hashset);
method3(hashset);
}
private static void method1(HashSet hashset) {
System.out.println("method1:");
for(Iterator it=hashset.iterator();it.hasNext();){
System.out.print(it.next()+" ");
}
System.out.println();
}
private static void method2(HashSet hashset) {
System.out.println("method2:");
Object [] arr=hashset.toArray();
for(Object i:arr){
System.out.print(i+" ");
}
System.out.println();
}
private static void method3(HashSet hashset) {
System.out.println("method3:");
for(int i:hashset){
System.out.print(i+" ");
}
}
}
三.遍历Hashtable(同步、线程安全的)
Hashtable table = new Hashtable();
table.put(1, "1");
table.put(2, "1");
table.put(3, "1");
//遍历key
Enumeration e = table.keys();
while( e. hasMoreElements() ){
System.out.println( e.nextElement() );
}
//遍历value
e = table.elements();
while( e. hasMoreElements() ){
System.out.println( e.nextElement() );
}