📜  Java中的 NavigableMap 接口与示例

📅  最后修改于: 2022-05-13 01:55:14.122000             🧑  作者: Mango

Java中的 NavigableMap 接口与示例

NavigableMap接口是Java集合框架的成员。它属于Java.util包,是SortedMap 的扩展,提供了lowerKey、floorKey、ceilingKey 和higherKey 等便捷的导航方法,以及这种流行的导航方法。它还提供了从Java中的现有 Map 创建 Sub Map 的方法,例如键小于指定键的 headMap,键大于指定键的 tailMap,以及严格包含介于 toKey 和 fromKey 之间的键的 subMap。
实现 NavigableMap 的示例类是 TreeMap。

宣言:

public interface NavigableMap extends SortedMap

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

NavigableMap 的层次结构

Java 中的 NavigableMap 接口与示例

它实现了 Map、SortedMap 接口。 ConcurrentNavigableMap 扩展 NavigableMap。 ConcurrentSkipListMap和 TreeMap 实现了 NavigableMap。

例子:

Java
// 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 nm
            = new TreeMap();
 
        // 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());
    }
}


Java
// 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 nmap
            = new TreeMap();
 
        // 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);
    }
}


Java
// 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 nmap
            = new TreeMap();
 
        // 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);
    }
}


Java
// 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 nmap
            = new TreeMap();
 
        // 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());
    }
}


Java
// 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 nmap
            = new TreeMap();
 
        // Add elements using put()
        nmap.put(3, "Geeks");
        nmap.put(2, "For");
        nmap.put(1, "Geeks");
 
        // Create an Iterator over the
        // NavigableMap
        Iterator > 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 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);
        }
    }
}



输出:

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 实现,它根据其键的自然顺序或在地图创建时提供的 Comparator 进行排序,具体取决于使用的构造函数。 TreeMap 的插入、删除和访问操作的预期时间成本为log(n) 。 TreeMap 不同步,必须在外部完成。

句法:

NavigableMap objectName = new TreeMap();

NavigableMap 的基本操作

1.添加元素

要将元素添加到 NavigableMap,我们可以使用 Map 接口的任何方法。下面的代码展示了如何使用它们。您可以在代码中观察到没有保留插入顺序。当构建时没有提供 Comparator 时,遵循自然顺序。

Java

// 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 nmap
            = new TreeMap();
 
        // 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

// 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 nmap
            = new TreeMap();
 
        // 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

// 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 nmap
            = new TreeMap();
 
        // 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 接口来遍历 Collection Framework 的任何结构。由于迭代器使用一种类型的数据,我们使用 Entry< ? , ? > 将两种不同的类型解析为兼容的格式。然后使用 next() 方法我们打印 NavigableMap 的元素。另一种著名的方法是使用 for-each 循环并获取密钥。键的值是通过使用 getValue() 方法找到的。

Java

// 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 nmap
            = new TreeMap();
 
        // Add elements using put()
        nmap.put(3, "Geeks");
        nmap.put(2, "For");
        nmap.put(1, "Geeks");
 
        // Create an Iterator over the
        // NavigableMap
        Iterator > 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 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 – 映射中映射的值的类型。

METHOD

DESCRIPTION

ceilingEntry(K key)Returns a key-value mapping associated with the least key greater than or equal to the given key, or null if there is no such key.
ceilingKey(K key)Returns the least key greater than or equal to the given key, or null if there is no such key.
descendingKeySet()Returns a reverse order NavigableSet view of the keys contained in this map.
descendingMap()Returns a reverse order view of the mappings contained in this map.
firstEntry()Returns a key-value mapping associated with the least key in this map, or null if the map is empty.
floorEntry(K key)Returns a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key.
floorKey(K key)Returns the greatest key less than or equal to the given key, or null if there is no such key.
headMap(K toKey)Returns a view of the portion of this map whose keys are strictly less than toKey.
headMap(K toKey, boolean inclusive)Returns a view of the portion of this map whose keys are less than (or equal to, if inclusive is true) toKey.
higherEntry(K key)Returns a key-value mapping associated with the least key strictly greater than the given key, or null if there is no such key.
higherKey(K key)Returns the least key strictly greater than the given key, or null if there is no such key.
lastEntry()Returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
lowerEntry(K key)Returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.
lowerKey(K key)Returns the greatest key strictly less than the given key, or null if there is no such key.
navigableKeySet()Returns a NavigableSet view of the keys contained in this map.
pollFirstEntry()Removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.
pollLastEntry()Removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.

subMap(K fromKey, boolean 

fromInclusive, K toKey, boolean toInclusive)

Returns a view of the portion of this map whose keys range from fromKey to toKey.
subMap(K fromKey, K toKey)Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.
tailMap(K fromKey)Returns a view of the portion of this map whose keys are greater than or equal to fromKey.
 tailMap(K fromKey, boolean inclusive)Returns a view of the portion of this map whose keys are greater than (or equal to, if inclusive is true) fromKey.

从接口Java.util.SortedMap 继承的方法

METHOD

DESCRIPTION

comparator()Returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.
entrySet()Returns a Set view of the mappings contained in this map.
firstKey()Returns the first (lowest) key currently in this map.
keySet()Returns a Set view of the keys contained in this map.
lastKey()Returns the last (highest) key currently in this map.
values()Returns a Collection view of the values contained in this map.

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

METHOD

DESCRIPTION

clear()Removes all of the mappings from this map (optional operation).

compute(K key, BiFunction

V,? extends V> remappingFunction)

Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).

computeIfAbsent(K key, Function

extends V> mappingFunction)

If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
computeIfPresent(K key, BiFunction remappingFunction)If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
containsKey(Object key)Returns true if this map contains a mapping for the specified key.
containsValue(Object value)Returns true if this map maps one or more keys to the specified value.
equals(Object o)Compares the specified object with this map for equality.
forEach(BiConsumer action)Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
get(Object key)Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
getOrDefault(Object key, V defaultValue)Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
hashCode()Returns the hash code value for this map.
isEmpty()Returns true if this map contains no key-value mappings.
merge(K key, V value, BiFunction remappingFunction)If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
put(K key, V value)Associates the specified value with the specified key in this map (optional operation).
putAll(Map m)Copies all of the mappings from the specified map to this map (optional operation).
putIfAbsent(K key, V value)If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
remove(Object key)Removes the mapping for a key from this map if it is present (optional operation).
remove(Object key, Object value)Removes the entry for the specified key only if it is currently mapped to the specified value.
replace(K key, V value)Replaces the entry for the specified key only if it is currently mapped to some value.
replace(K key, V oldValue, V newValue)Replaces the entry for the specified key only if currently mapped to the specified value.
replaceAll(BiFunction function)Replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
size()Returns the number of key-value mappings in this map.