SoFunction
Updated on 2025-03-08

Example of Java

In Java, <K, V>  is a nested interface that exists in the Map interface. It represents a key-value pair in Map, which is often used to traverse or operate Map. The following is a detailed explanation of <K, V>.

1. What is <K, V>?

  • <K, V>yesMapA static nested interface in the interface.
  • expressMapA key-value pair in  .
  • Provides a method to get keys and values, allowing forMapThe key values ​​in iterate, operate, etc.

Interface definition

public static interface &lt;K, V&gt; {
    K getKey();      // Get key    V getValue();    // Get the value    V setValue(V value); // Set value    boolean equals(Object o); // Determine whether two Entry are equal    int hashCode();  // Return the hash value of Entry}

2. Detailed explanation of the method

2.1 getKey()

  • Return to the currentEntryKey in the object.
  • The return value is the type of key (K)。

2.2 getValue()

  • Return to the currentEntryValues ​​in the object.
  • Returns the type of value (V)。

2.3 setValue(V value)

  • Set the currentEntryvalue.
  • The return value is the previous old value.

2.4 equals(Object o)

  • Judge twoEntryWhether the objects are equal.
  • If twoEntryIf the keys and values ​​of   are equal, they are considered equal.

2.5 hashCode()

  • Return to the currentEntryhash value.
  • Usually calculated based on the hash value of keys and values.

3. Use scenarios

3.1 traversing the key-value pairs of Map

Usually used to passentrySet()TraversalMapkey-value pair.

import ;
import ;

public class EntryExample {
    public static void main(String[] args) {
        Map&lt;String, Integer&gt; map = new HashMap&lt;&gt;();
        ("Apple", 1);
        ("Banana", 2);
        ("Cherry", 3);

        // Use entrySet to traverse        for (&lt;String, Integer&gt; entry : ()) {
            ("Key: " + () + ", Value: " + ());
        }
    }
}

Output

Key: Apple, Value: 1
Key: Banana, Value: 2
Key: Cherry, Value: 3

3.2 Modify the value of Map

passsetValue()Modify the value:

import ;
import ;

public class ModifyEntryExample {
    public static void main(String[] args) {
        Map&lt;String, Integer&gt; map = new HashMap&lt;&gt;();
        ("A", 10);
        ("B", 20);

        // traverse and modify the value        for (&lt;String, Integer&gt; entry : ()) {
            (() * 2); // Multiply the value by 2        }

        (map); // Output: {A=20, B=40}    }
}

3.3 Conditional Operation

Filter or delete specific key-value pairs by conditional operations:

import ;
import ;

public class ConditionalOperationExample {
    public static void main(String[] args) {
        Map&lt;String, Integer&gt; map = new HashMap&lt;&gt;();
        ("X", 100);
        ("Y", 200);
        ("Z", 300);

        // Delete key-value pairs with values ​​less than 200        ().removeIf(entry -&gt; () &lt; 200);

        (map); // Output: {Y=200, Z=300}    }
}

3.4 Customize equals and hashCode

ofequalsandhashCodeUsually it has a role in set operations (such as search and deduplication):

import ;
import ;
import ;
import ;

public class EntryEqualsExample {
    public static void main(String[] args) {
        Set&lt;&lt;String, Integer&gt;&gt; set = new HashSet&lt;&gt;();

        (new &lt;&gt;("A", 1));
        (new &lt;&gt;("B", 2));
        (new &lt;&gt;("A", 1)); // repeat
        (()); // Output: 2 (There are only two Entry after deduplication)    }
}

4. Commonly used implementation classes

It is an interface, and common implementation classes include:

4.1 <K, V>

  • Used to store a simple key-value pair.
  • Provides variable keys and values.

Example

import ;

public class SimpleEntryExample {
    public static void main(String[] args) {
        &lt;String, Integer&gt; entry = new &lt;&gt;("Key", 100);

        ("Key: " + ()); // Output: Key        ("Value: " + ()); // Output: 100
        (200);
        ("Updated Value: " + ()); // Output: 200    }
}

4.2 <K, V>

  • Used to store immutable key-value pairs.
  • Once created, the keys and values ​​cannot be modified.

Example

import ;

public class SimpleImmutableEntryExample {
    public static void main(String[] args) {
        &lt;String, Integer&gt; entry = new &lt;&gt;("Key", 100);

        ("Key: " + ()); // Output: Key        ("Value: " + ()); // Output: 100
        // (200); // Compile error, value cannot be modified    }
}

5. Common operations and efficiency

performance

  • useentrySet()Traveling is more than direct callkeySet()orvalues()Efficient, becauseentrySet()Traveling to get keys and values ​​at the same time, without additional searches.

Applicable scenarios

  • Keys and values ​​need to be operated simultaneously.
  • When modifying or filtering key-value pairs.

6. Summary

advantage

  • <K, V>Provides an elegant way to traverse and operateMapkey-value pair.
  • CombinedentrySet(), can obtain keys and values ​​efficiently at the same time.
  • By implementing classes (such asSimpleEntryandSimpleImmutableEntry), can be found inMapflexibly use key-value pairs outside.

Applicable scenarios

  • TraversalMap
  • Modify or filter key-value pairs.
  • When using custom key-value pair logic.

<K, V> is the core tool for handling key-value pairs in the Java collection framework and is the basis for efficient operation of Map.

This is the end of this article about the specific use of java. For more related java content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!