NavigableMap.headMap()的用法

Java中NavigableMap接口的headMap()方法用于返回此Map的一部分,其键小于(或等于,如果包含,则为true)toKey的map

 

NavigableMap<K, V> headMap(K toKey,
                          boolean inclusive)

参数:此函数接受两个参数:

  • toKey:此参数指的是 key 。
  • inclusive:此参数决定是否将要删除的 key 与相等进行比较。

返回值:返回此Map部分的视图,该视图的键小于(或等于,如果包含在内,则为true)toKey。

 

程序1:当键为整数且缺少第二个参数时。

// Java code to demonstrate the working of 
// headMap?() method 
  
import java.io.*; 
import java.util.*; 
  
public class GFG { 
  
    public static void main(String[] args) 
    { 
  
        // Declaring the NavigableMap of Integer and String 
        NavigableMap<Integer, String> nmmp = new TreeMap<>(); 
  
        // assigning the values in the NavigableMap 
        // using put() 
        nmmp.put(2, "two"); 
        nmmp.put(7, "seven"); 
        nmmp.put(3, "three"); 
  
        System.out.println("View of map with key less than"
                      + " or equal to 7 : " + nmmp.headMap(7)); 
    } 
}

 

 
输出:
View of map with key less than or equal to 7 : {2=two, 3=three}

程序2:带有第二个参数。

 
// Java code to demonstrate the working of 
// headMap?() method 
  
import java.io.*; 
import java.util.*; 
  
public class GFG { 
  
    public static void main(String[] args) 
    { 
  
        // Declaring the NavigableMap of Integer and String 
        NavigableMap<Integer, String> nmmp = new TreeMap<>(); 
  
        // assigning the values in the NavigableMap 
        // using put() 
        nmmp.put(2, "two"); 
        nmmp.put(7, "seven"); 
        nmmp.put(3, "three"); 
        nmmp.put(9, "nine"); 
  
        // headMap with second argument as true 
        System.out.println("View of map with key less than"
                     + " or equal to 7 : " + nmmp.headMap(7, true)); 
    } 
}

 

输出:
View of map with key less than or equal to 7 : {2=two, 3=three, 7=seven}

参考: https://docs.oracle.com/javase/10/docs/api/java/util/NavigableMap.html#headMap(K, boolean)

 

 

posted @ 2024-02-25 15:56  r1-12king  阅读(6)  评论(0编辑  收藏  举报