HashMap的四种遍历!
HashMap的四种遍历
import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Map接口: * 1.键值对存储一组对象 * 2.key必须保证唯一,Value可以重复 * 3.具体实现类:HashMap TreeMap Hashtable LinkedHashMap * HashMap 类不保证顺序 * @author 给个赞呗!!!!!!!!!!!!!!!!!!!!!!!!!! * @date 2019/8/12 21:22 */ public class Map09 { public static void main(String[] args){ hashMap(); } private static void hashMap(){ Map<Integer,String> map=new HashMap<>();//Map<key,value> map.put(1,"HashMap"); map.put(2,"无序的"); map.put(3,"put方法"); System.out.println(map.size()); System.out.println("得到key=2的值:"+map.get(2)); //第一种遍历 lambda表达式遍历forEach();非常简便 map.forEach((i, s) -> System.out.println("key="+i+" 值:"+s)); //第二种遍历 遍历Entry Set<Map.Entry<Integer,String>> entry=map.entrySet(); for (Map.Entry e:entry){ System.out.println(e.getKey()+"->"+e.getValue()); } //输出entry System.out.println(entry); //第三种 遍历键 map.keySet() Set<Integer> key=map.keySet(); for (Integer i:key){ String va=map.get(i); System.out.println(i+"->"+va); } //第四种遍历值map.values() Collection<String> vs=map.values(); for (String str:vs){ System.out.println(str); } } }