要从TreeMap获取Tail Map,让我们首先创建一个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");
现在,假设您需要从2获取尾图,即2之后的所有键值对。为此,请使用方法tailMap()
-
SortedMapmap = tMap.tailMap("2");
import java.util.SortedMap; import java.util.TreeMap; public class Demo { public static void main(String[] args) { TreeMap<String, String>tMap = new TreeMap(); 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 map = tMap.tailMap("2"); System.out.println("Sub Map = " + map); map = tMap.tailMap("8"); System.out.println("Sub Map = " + map); map = tMap.tailMap("1"); System.out.println("Sub Map = " + map); } }
输出结果
Sub Map = {2=B, 3=C, 4=D, 5=E, 6=F, 7=G, 8=H, 9=I} Sub Map = {8=H, 9=I} Sub Map = {1=A, 10=J, 2=B, 3=C, 4=D, 5=E, 6=F, 7=G, 8=H, 9=I}