Java NavigableMap接口与实例

Java NavigableMap接口与实例

NavigableMap 接口是Java集合框架的一个成员。它属于 java.util 包,是SortedMap的扩展,提供了方便的导航方法,如lowerKey, floorKey, ceilingKey和higherKey,以及与此相关的流行导航方法。它还提供了从现有的Java地图中创建子地图的方法,例如,键值小于指定键值的headMap,键值大于指定键值的tailMap,以及严格包含键值在toKey和fromKey之间的子地图。
实现NavigableMap的实例类是TreeMap。

声明

public interface NavigableMap<K,V> extends SortedMap<K,V>

这里, K 是键对象类型, V 是值对象类型。

NavigableMap的层次结构

Java中的NavigableMap接口与实例

它实现了Map<K,V>, SortedMap<K,V>接口。ConcurrentNavigableMap<K,V> 扩展了NavigableMap。 ConcurrentSkipListMap 和TreeMap实现了NavigableMap。

例子

// Java program to demonstrate
// the NavigableMap interface
import java.util.NavigableMap;
import java.util.TreeMap;
 
public class NavigableMapExample {
 
    public static void main(String[] args)
    {
        // Instantiate an object
        // Since NavigableMap
        // is an interface so we
        // use TreeMap
        NavigableMap<String, Integer> nm
            = new TreeMap<String, Integer>();
 
        // Add elements using put() method
        nm.put("C", 888);
        nm.put("Y", 999);
        nm.put("A", 444);
        nm.put("T", 555);
        nm.put("B", 666);
        nm.put("A", 555);
 
        // Print the contents on the console
        System.out.println("Mappings of NavigableMap : "
                           + nm);
 
        System.out.printf("Descending Set  : %s%n",
                          nm.descendingKeySet());
        System.out.printf("Floor Entry  : %s%n",
                          nm.floorEntry("L"));
        System.out.printf("First Entry  : %s%n",
                          nm.firstEntry());
        System.out.printf("Last Key : %s%n", nm.lastKey());
        System.out.printf("First Key : %s%n",
                          nm.firstKey());
        System.out.printf("Original Map : %s%n", nm);
        System.out.printf("Reverse Map : %s%n",
                          nm.descendingMap());
    }
}

输出

Mappings of NavigableMap : {A=555, B=666, C=888, T=555, Y=999}
Descending Set  : [Y, T, C, B, A]
Floor Entry  : C=888
First Entry  : A=555
Last Key : Y
First Key : A
Original Map : {A=555, B=666, C=888, T=555, Y=999}
Reverse Map : {Y=999, T=555, C=888, B=666, A=555}

实现类

NavigableMap有两个实现类,即 ConcurrentSkipListMapTreeMap。 TreeMap是一个基于红黑树的NavigableMap实现,它根据其键的自然排序进行排序,或者根据地图创建时提供的比较器进行排序,这取决于使用哪个构造函数。 TreeMap的插入、删除和访问操作的预期时间成本为 log(n) 。TreeMap是不同步的,必须在外部完成。

语法

NavigableMap<K, V> objectName = new TreeMap<K, V>();

对NavigableMap的基本操作

1.添加元素

为了向NavigableMap添加元素,我们可以使用Map接口的任何方法。下面的代码显示了如何使用它们。你可以在代码中观察到,插入的顺序没有被保留。当构造时没有提供比较器时,自然的顺序被遵循。

// Java program for adding elements
// to a NavigableMap
import java.util.*;
 
class AddingElementsExample {
    public static void main(String args[])
    {
 
        // Instantiate an object
        // Since NavigableMap is an interface
        // We use TreeMap
        NavigableMap<Integer, String> nmap
            = new TreeMap<Integer, String>();
 
        // Add elements using put()
        nmap.put(3, "Geeks");
        nmap.put(2, "For");
        nmap.put(1, "Geeks");
 
        // Print the contents on the console
        System.out.println("Mappings of NavigableMap : "
                           + nmap);
    }
}

输出

Mappings of NavigableMap : {1=Geeks, 2=For, 3=Geeks}

2.删除元素

要删除元素,我们也要使用Map接口的方法,因为NavigableMap是Map的子嗣。我们可以使用remove()方法,该方法接收键值,如果该键存在于地图上,则将其从该树状图中删除。我们可以使用clear()来删除地图中的所有元素。

// Java Program for deleting
// elements from NavigableMap
import java.util.*;
 
class RemovingElementsExample {
   
    public static void main(String args[])
    {
        // Instantiate an object
        // Since NavigableMap
        // is an interface
        // We use TreeMap
        NavigableMap<Integer, String> nmap
            = new TreeMap<Integer, String>();
 
        // Add elements using put()
        nmap.put(3, "Geeks");
        nmap.put(2, "Geeks");
        nmap.put(1, "Geeks");
        nmap.put(4, "For");
 
        // Print the contents on the console
        System.out.println("Mappings of NavigableMap : "
                           + nmap);
 
        // Remove elements using remove()
        nmap.remove(4);
 
        // Print the contents on the console
        System.out.println(
            "\nNavigableMap, after remove operation : "
            + nmap);
 
        // Clear the entire map using clear()
        nmap.clear();
        System.out.println(
            "\nNavigableMap, after clear operation : "
            + nmap);
    }
}

输出

Mappings of NavigableMap : {1=Geeks, 2=Geeks, 3=Geeks, 4=For}

NavigableMap, after remove operation : {1=Geeks, 2=Geeks, 3=Geeks}

NavigableMap, after clear operation : {}

3.访问元素

我们可以使用get()方法访问NavigableMap中的元素,下面给出了这个例子。

// Java Program for accessing
// elements in a NavigableMap
 
import java.util.*;
 
public class AccessingElementsExample {
 
    public static void main(String[] args)
    {
        // Instantiate an object
        // Since NavigableMap is an interface
        // We use TreeMap
        NavigableMap<Integer, String> nmap
            = new TreeMap<Integer, String>();
 
        // Add elements using put()
        nmap.put(8, "Third");
        nmap.put(6, "Second");
        nmap.put(3, "First");
        nmap.put(11, "Fourth");
 
        // Accessing the elements using get()
        // with key as a parameter
        System.out.println(nmap.get(3));
        System.out.println(nmap.get(6));
        System.out.println(nmap.get(8));
        System.out.println(nmap.get(11));
 
        // Display the set of keys using keySet()
        System.out.println("\nThe NavigableMap key set: "
                           + nmap.keySet());
    }
}

输出

First
Second
Third
Fourth

The NavigableMap key set: [3, 6, 8, 11]

4.遍历

我们可以使用Iterator接口来遍历集合框架的任何结构。由于迭代器只处理一种类型的数据,我们使用Entry< ?, ? >来将两种不同的类型解析成一种兼容的格式。然后使用next()方法,我们打印NavigableMap的元素。另一个著名的方法是使用for-each循环并获得键。通过使用getValue()方法可以找到键的值。

// Java Program for traversing
// a NavigableMap
import java.util.*;
 
class TraversalExample {
   
    public static void main(String args[])
    {
        // Instantiate an object
        // Since NavigableMap is an interface
        // We use TreeMap
        NavigableMap<Integer, String> nmap
            = new TreeMap<Integer, String>();
 
        // Add elements using put()
        nmap.put(3, "Geeks");
        nmap.put(2, "For");
        nmap.put(1, "Geeks");
 
        // Create an Iterator over the
        // NavigableMap
        Iterator<NavigableMap.Entry<Integer, String> > itr
            = nmap.entrySet().iterator();
 
        System.out.println("Traversing using Iterator: ");
        // The hasNext() method is used to check if there is
        // a next element The next() method is used to
        // retrieve the next element
        while (itr.hasNext()) {
            NavigableMap.Entry<Integer, String> entry
                = itr.next();
            System.out.println("Key = " + entry.getKey()
                               + ", Value = "
                               + entry.getValue());
        }
 
        System.out.println("Traversing using for-each: ");
        // Iterate using for-each loop
        for (Map.Entry mapElement : nmap.entrySet()) {
            // get the key using getKey()
            int key = (int)mapElement.getKey();
 
            // Finding the value
            String value = (String)mapElement.getValue();
 
            System.out.println("Key = " + key
                               + ", Value = " + value);
        }
    }
}

输出

Traversing using Iterator:  
Key = 1, Value = Geeks
Key = 2, Value = For
Key = 3, Value = Geeks
Traversing using for-each:  
Key = 1, Value = Geeks
Key = 2, Value = For
Key = 3, Value = Geeks

注意: 每次我们说 “NavigableMap的元素 “时,必须注意这些元素实际上是存储在NavigableMap的一个实现类的对象中,这里是TreeMap。

NavigableMap的方法

NavigableMap继承了Map接口和SortedMap接口的方法。添加元素、删除元素和遍历的基本方法由父接口给出。NavigableMap的方法在下表中给出。这里

  • K – 地图中键的类型。
  • V – 地图中映射的值的类型。
方法 描述
ceilingEntry(K key) 返回一个与大于或等于给定键的最小键相关的键值映射,如果没有这样的键,则返回空。
ceilingKey(K key) 返回大于或等于给定键的最小键,如果没有这样的键,则返回null。
descendingKeySet() 返回该地图中包含的键的反向顺序NavigableSet视图。
descendingMap() 返回该地图中包含的映射的倒序视图。
firstEntry() 返回与该地图中最小的键相关的键值映射,如果该地图为空,则返回空。
floorEntry(K key) 返回一个与小于或等于给定键的最大键相关的键值映射,如果没有这样的键,则返回null。
floorKey(K key) 返回小于或等于给定键的最大键,如果没有这样的键,则返回null。
headMap(K toKey) 返回该地图中键值严格小于toKey的部分的视图。
headMap(K toKey, boolean inclusive) 返回该地图中键值小于(或等于,如果包容性为真)toKey的部分的视图。
higherEntry(K key) 返回一个与严格大于给定键的最小键相关的键值映射,如果没有这样的键,则返回空。
higherKey(K key) 返回严格大于给定键的最小键,如果没有这样的键,则返回null。
LastEntry() 返回与该地图中最大键相关的键值映射,如果该地图为空,则返回null。
lowerEntry(K key) 返回一个与严格小于给定键的最大键相关的键值映射,如果没有这样的键,则返回null。
lowerKey(K key) 返回严格小于给定键的最大键,如果没有这样的键,则为空。
navigableKeySet() 返回这个地图中包含的键的NavigableSet视图。
pollFirstEntry() 删除并返回与该地图中最小的键相关的键值映射,如果地图为空,则返回null。
pollLastEntry() 删除并返回与该地图中最大键相关的键值映射,如果地图为空,则为空。
subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) 返回该地图中键值范围从fromKey到toKey的部分的视图。
subMap(K fromKey, K toKey) 返回该地图中键值范围从fromKey(包括)到toKey(不包括)的部分的视图。
tailMap(K fromKey) 返回该地图中键值大于或等于fromKey的部分的视图。
tailMap(K fromKey, boolean inclusive) 返回该地图中键值大于(或等于,如果包容性为真)fromKey的部分的视图。

从java.util.SortedMap界面继承的方法

方法 描述
comparator() 返回用于对该地图中的键进行排序的比较器,如果该地图使用其键的自然排序,则返回空。
entrySet() 返回该地图中包含的映射的Set视图。
firstKey() 返回当前该地图中的第一个(最低)键。
keySet() 返回该地图中包含的键的集合视图。
lastKey() 返回当前地图中的最后一个(最高)键。
values() 返回该地图中包含的值的集合视图。

从java.util.Map接口继承的方法

方法 描述
clear() 删除该地图中的所有映射(可选操作)。
compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) 试图为指定的键和其当前的映射值计算一个映射(如果没有当前的映射,则为空)。
computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) 如果指定的键还没有与一个值相关联(或者被映射为空),则尝试使用给定的映射函数计算其值,并将其输入此映射,除非为空。
computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) 如果指定的键的值是存在的,并且不是空的,则尝试计算一个新的映射,给定键和它当前的映射值。
containsKey(Object key) 如果这个地图包含指定键的映射,返回true。
containsValue(Object value) 如果这个地图将一个或多个键映射到指定的值,则返回true。
equals(Object o) 将指定的对象与这个映射进行比较,看是否相等。
forEach(BiConsumer<? super K,? super V> action) 对这个地图中的每个条目执行给定的动作,直到所有条目都被处理完,或者该动作抛出一个异常。
get(Object key) 返回指定的键所映射的值,如果这个地图不包含键的映射,则返回空值。
getOrDefault(Object key, V defaultValue) 返回指定的键所映射的值,如果这个地图不包含键的映射,则返回defaultValue。
hashCode() 返回这个地图的哈希代码值。
isEmpty() 如果这个地图不包含键值映射,则返回true。
merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) 如果指定的键还没有与一个值相关联,或者与空值相关联,则将其与给定的非空值相关联。
put(K key, V value) 将指定的值与该地图中的指定键关联起来(可选操作)。
putAll(Map<? extends K,? extends V> m) 将指定地图中的所有映射复制到此地图中(可选操作)。
putIfAbsent(K key, V value) 如果指定的key还没有与一个值相关联(或者被映射为null),则将其与给定的值相关联并返回null,否则返回当前值。
remove(Object key) 如果键存在的话,从这个地图中删除键的映射(可选操作)。
remove(Object key, Object value) 只有当指定的键当前被映射到指定的值时,才会删除该键的条目。
replace(K key, V value) 仅当指定的键当前被映射到某个值时,替换该键的条目。
replace(K key, V oldValue, V newValue) 只在当前映射到指定值的情况下替换指定键的条目。
replaceAll(BiFunction<? super K,? super V,? extends V> function) 用对该条目调用给定函数的结果替换每个条目的值,直到所有条目都被处理完,或者该函数抛出一个异常。
size() 返回该地图中键值映射的数量。

参考资料 : https://docs.oracle.com/javase/8/docs/api/java/util/NavigableMap.html

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程