要从TreeMap获取子映射,让我们首先创建一个TreeMap并设置键值对-
TreeMap<String, String>tMap = new TreeMap<String, String>(); tMap.put("1", "A"); tMap.put("2", "B"); tMap.put("3", "C"); tMap.put("4", "D"); tMap.put("5", "E"); tMap.put("6", "F"); tMap.put("7", "G");
现在,假设您需要将子图从3映射到7。为此,请使用submap()
-
=SortedMap<String, String>map = tMap.subMap("3", "7");
import java.util.SortedMap; import java.util.TreeMap; public class Demo { public static void main(String[] args) { TreeMap<String, String>tMap = new TreeMap<String, String>(); tMap.put("1", "A"); tMap.put("2", "B"); tMap.put("3", "C"); tMap.put("4", "D"); tMap.put("5", "E"); tMap.put("6", "F"); tMap.put("7", "G"); tMap.put("8", "H"); tMap.put("9", "I"); tMap.put("10", "J"); SortedMap<String, String>map = tMap.subMap("3", "7"); System.out.println("SortedMap = " + map); map = tMap.subMap("5", "7"); System.out.println("SortedMap = " + map); map = tMap.subMap("8", "8"); System.out.println("SortedMap = " + map); } }
输出结果
SortedMap= {3=C, 4=D, 5=E, 6=F} SortedMap = {5=E, 6=F} SortedMap = {}