当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java TreeMap navigableKeySet()用法及代码示例


java.util.TreeMap类的navigableKeySet()方法用于返回此映射中包含的键的NavigableSet视图。

集合的迭代器以升序返回 key 。该集合由Map支持,因此对Map的更改会反映在集合中,反之亦然。如果在对集合进行迭代时修改了Map(通过迭代器自己的remove操作除外),则迭代的结果是不确定的。该集合支持元素删除,该元素通过Iterator.remove,Set.remove,removeAll,retainAll和clear操作从映射中删除相应的映射。它不支持add或addAll操作。

用法:


public NavigableSet navigableKeySet()

返回值:此方法返回此映射中的键的可导航设置视图。

以下示例说明了navigableKeySet()方法

示例1:

// Java program to demonstrate 
// navigableKeySet() method 
// for Integer value key 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) 
        throws Exception 
    { 
  
        try { 
  
            // creating object of TreeMap<Integer, String> 
            TreeMap<Integer, String> 
                treemap = new TreeMap<Integer, String>(); 
  
            // populating tree map 
            treemap.put(1, "One"); 
            treemap.put(2, "Two"); 
            treemap.put(3, "Three"); 
            treemap.put(4, "Four"); 
            treemap.put(5, "Five"); 
  
            // pritnig the TreeMap 
            System.out.println("TreeMap: " + treemap); 
  
            // getting navigable set view of the keys 
            // using navigableKeySet() method 
            NavigableSet<Integer> 
                value = treemap.navigableKeySet(); 
  
            // printing the value 
            System.out.println("Value is: " + value); 
        } 
  
        catch (NullPointerException e) { 
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
输出:
TreeMap: {1=One, 2=Two, 3=Three, 4=Four, 5=Five}
Value is: [1, 2, 3, 4, 5]

示例2:

// Java program to demonstrate 
// navigableKeySet() method 
// for String value key 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) 
        throws Exception 
    { 
  
        try { 
  
            // creating object of TreeMap<Integer, String> 
            TreeMap<String, Integer> 
                treemap = new TreeMap<String, Integer>(); 
  
            // populating tree map 
            treemap.put("A", 1); 
            treemap.put("B", 2); 
            treemap.put("C", 3); 
            treemap.put("D", 4); 
            treemap.put("E", 5); 
  
            // pritnig the TreeMap 
            System.out.println("TreeMap: " + treemap); 
  
            // getting navigable set view of the keys 
            // using navigableKeySet() method 
            NavigableSet<String> 
                value = treemap.navigableKeySet(); 
  
            // printing the value 
            System.out.println("Value is: " + value); 
        } 
  
        catch (NullPointerException e) { 
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
输出:
TreeMap: {A=1, B=2, C=3, D=4, E=5}
Value is: [A, B, C, D, E]


相关用法


注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 TreeMap navigableKeySet() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。