原文: https://beginnersbook.com/2014/08/java-get-set-view-of-keys-from-hashmap/

描述

程序从HashMap获取键集。

示例

  1. import java.util.Iterator;
  2. import java.util.HashMap;
  3. import java.util.Set;
  4. class HashMapExample{
  5. public static void main(String args[]) {
  6. // Create a HashMap
  7. HashMap<String, String> hmap = new HashMap<String, String>();
  8. // Adding few elements
  9. hmap.put("Key1", "Jack");
  10. hmap.put("Key2", "Rock");
  11. hmap.put("Key3", "Rick");
  12. hmap.put("Key4", "Smith");
  13. hmap.put("Key5", "Will");
  14. // Getting Set of HashMap keys
  15. /* public Set<K> keySet(): Returns a Set view of the keys contained
  16. * in this map. The set is backed by the map, so changes to the map
  17. * are reflected in the set, and vice-versa.
  18. */
  19. Set<String> keys = hmap.keySet();
  20. System.out.println("Set of Keys contains: ");
  21. /* If your HashMap has integer keys then specify the iterator like
  22. * this: Iterator<Integer> it = keys.iterator();
  23. */
  24. Iterator<String> it = keys.iterator();
  25. // Displaying keys. Output will not be in any particular order
  26. while(it.hasNext()){
  27. System.out.println(it.next());
  28. }
  29. }
  30. }

输出:

  1. Set of Keys contains:
  2. Key2
  3. Key1
  4. Key4
  5. Key3
  6. Key5

注意:这组键由原始HashMap备份,因此如果从Set中删除任何键,它将自动从HashMap中删除。