从Java中的TreeMap获取子映射
要使用Java获取SubMap,请使用submap()
方法。它返回Map范围内的元素。
首先,创建一个TreeMap并添加元素-
TreeMap<Integer,String> m = new TreeMap<Integer,String>(); m.put(1,"PHP"); m.put(2,"jQuery"); m.put(3,"JavaScript"); m.put(4,"Ruby"); m.put(5,"Java"); m.put(6,"AngularJS"); m.put(7,"ExpressJS");
现在,获取4到6之间的子贴图-
m.subMap(4, 6)
以下是从Java树形图获取子图的示例
示例
import java.util.*; public class Demo { public static void main(String args[]){ TreeMap<Integer,String> m = new TreeMap<Integer,String>(); m.put(1,"PHP"); m.put(2,"jQuery"); m.put(3,"JavaScript"); m.put(4,"Ruby"); m.put(5,"Java"); m.put(6,"AngularJS"); m.put(7,"ExpressJS"); System.out.println("TreeMap Elements...\n"+m); System.out.println("Sub Map = " + m.subMap(4, 6)); } }
输出结果
TreeMap Elements... {1=PHP, 2=jQuery, 3=JavaScript, 4=Ruby, 5=Java, 6=AngularJS, 7=ExpressJS} Sub Map = {4=Ruby, 5=Java}