本篇讲述的是map的基本使用
1.概述
2.Map的获取功能
3.遍历
方式1:
HashMap<String, String> hashMap = new HashMap<>(); hashMap.put("001","张飞"); hashMap.put("002","关于"); hashMap.put("003","赵云"); Set<String> stringSet = hashMap.keySet(); for (String key:stringSet){ System.out.println(key+":"+hashMap.get(key)); }
方式2:
Set<Map.Entry<String, String>> entries = hashMap.entrySet(); for (Map.Entry<String, String> m:entries){ System.out.println(m.getKey()+":"+m.getValue()); }
方式3:
只获取值
26. System.out.println("通过Map.values()遍历所有的value,但不能遍历key"); 27. for (String v : map.values()) { 28. System.out.println("value= " + v); 29. } 30. }
方式4:
/** * default void forEach(BiConsumer<? super K,? super V> action) * 对此映射中的每个条目执行给定操作,直到处理完所有条目或操作引发异常。 * BiConsumer: * 这是一个功能接口,因此可以用作lambda表达式或方法引用的赋值目标。 * -------------------------------------------------------------------------------- * @FunctionalInterface * public interface BiConsumer<T,U> * 其功能方法是accept(Object, Object) 。 */ public class HashMapLearn { public static void main(String[] args) { HashMap<String, String> hashMap = new HashMap<>(); hashMap.put("1", "1"); hashMap.put("2", "2"); hashMap.put("3", "3"); hashMap.put("4", "4"); hashMap.forEach((key, value) -> { System.out.println(key + ":" + value); }); }
补充:
Map.Entry是Map声明的一个内部接口,此接口为泛型,定义为Entry<K,V>。它表示Map中的一个实体(一个key-value对)。接口中有getKey(),getValue方法。
HashMap的源码中发现了Entry的定义,原来他是HashMap的一个内部类,并且实现了Map.Entry接口:
1.static class Entry<K,V> implements Map.Entry<K,V> { 2. final K key; 3. V value; 4. Entry<K,V> next; 5. final int hash; 6. 7. /** 8. * Creates new entry. 9. */ 10. Entry(int h, K k, V v, Entry<K,V> n) { 11. value = v; 12. next = n; 13. key = k; 14. hash = h; 15. } 16. 17. public final K getKey() { 18. return key; 19. } 20. 21. public final V getValue() { 22. return value; 23. }