Java SortedMap size()方法及示例
Java中 SortedMap接口 的 size() 方法用于获取SortedMap的大小,即SortedMap中的键值对或映射的数量。
语法
int size()
参数: 该方法不接受任何参数。
返回值: 该方法返回SortedMap的 大小 ,也就是SortedMap中存在的键值对的数量。
注意 :SortedMap中的size()方法是从Java中的Map接口继承来的。
以下程序说明了size()方法的工作原理。
程序1 :将字符串值映射到整数键。
// Java code to illustrate the size() method import java.util.*; public class Gfg { public static void main(String[] args) { // Creating an empty SortedMap SortedMap<Integer, String> map = new TreeMap<Integer, String>(); // Mapping string values to int keys map.put(10, "Geeks"); map.put(15, "4"); map.put(20, "Geeks"); map.put(25, "Welcomes"); map.put(30, "You"); // Displaying the SortedMap System.out.println( "Initial Mappings are: " + map); // Displaying the size of the map System.out.println( "The size of the map is " + map.size()); }}
输出:
Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}The size of the map is 5程序2: 将整数值映射到字符串键。
// Java code to illustrate the size() method import java.util.*; public class Gfg { public static void main(String[] args) { // Creating an empty SortedMap SortedMap<String, Integer> map = new TreeMap<String, Integer>(); // Mapping int values to string keys map.put("Geeks", 10); map.put("4", 15); map.put("Geeks", 20); map.put("Welcomes", 25); map.put("You", 30); // Displaying the SortedMap System.out.println( "Initial Mappings are: " + map); // Displaying the size of the map System.out.println( "The size of the map is " + map.size()); }}输出:
Initial Mappings are: {4=15, Geeks=20, Welcomes=25, You=30}The size of the map is 4注意: 同样的操作可以通过不同数据类型的变化和组合对任何类型的Mapping进行操作。
参考资料: https://docs.oracle.com/javase/9/docs/api/java/util/Map.html#size-
