原文: https://beginnersbook.com/2014/07/how-to-get-the-sub-map-from-treemap-example-java/

在这个例子中,我们将看到如何从TreeMap获取子映射。我们正在使用TreeMap类的subMap()方法。有关详细信息,请参阅以下程序中的注释。

示例

  1. import java.util.*;
  2. class TreeMapDemo {
  3. public static void main(String args[]) {
  4. // Create a TreeMap
  5. TreeMap<String, String> treemap =
  6. new TreeMap<String, String>();
  7. // Put elements to the map
  8. treemap.put("Key1", "Jack");
  9. treemap.put("Key2", "Rick");
  10. treemap.put("Key3", "Kate");
  11. treemap.put("Key4", "Tom");
  12. treemap.put("Key5", "Steve");
  13. treemap.put("Key6", "Ram");
  14. // Displaying TreeMap elements
  15. System.out.println("TreeMap Contains : " + treemap);
  16. // Getting the sub map
  17. /* public SortedMap<K,V> subMap(K fromKey,K toKey): Returns
  18. * a view of the portion of this map whose keys range from
  19. * fromKey, inclusive, to toKey, exclusive.
  20. * (If fromKey and toKey are equal, the returned map is empty.)
  21. * The returned map is backed by this map, so changes in the
  22. * returned map are reflected in this map, and vice-versa.
  23. * The returned map supports all optional map operations that
  24. * this map supports.
  25. */
  26. SortedMap<String, String> sortedMap = treemap.subMap("Key2","Key5");
  27. System.out.println("SortedMap Contains : " + sortedMap);
  28. // Removing an element from Sub Map
  29. sortedMap.remove("Key4");
  30. /* Displaying elements of original TreeMap after
  31. * removing an element from the Sub Map. Since Sub Map is
  32. * backed up by original Map, the element should be removed
  33. * from this TreeMap too.
  34. */
  35. System.out.println("TreeMap Contains : " + treemap);
  36. }
  37. }

输出:

  1. TreeMap Contains : {Key1=Jack, Key2=Rick, Key3=Kate, Key4=Tom, Key5=Steve, Key6=Ram}
  2. SortedMap Contains : {Key2=Rick, Key3=Kate, Key4=Tom}
  3. TreeMap Contains : {Key1=Jack, Key2=Rick, Key3=Kate, Key5=Steve, Key6=Ram}

参考:

subMap()方法 - TreeMap javadoc)
SortedMap javadoc