Saturday, November 15, 2025
HomeLanguagesJavaJavaTuples setKey() method

JavaTuples setKey() method

The setKey() method in org.javatuples is used to set the key of the KeyValue Class object. This method can be used with only KeyValue class object of javatuples library. It returns another KeyValueClassObject with the Key as the element passed as the parameter, and the value from the previous KeyValueClassObject.

Method Declaration:

public <X> KeyValue<X, B> setKey(X key)

Syntax:

KeyValue<X, B> KeyValueClassObject = KeyValue.setKey(X key)

Return Value: This method returns another KeyValueClassObject with the Key as the element passed as the parameter, and the value from the previous KeyValueClassObject.

Below programs illustrate the various ways to use setKey() method:

Example 1:




// Below is a Java program to set
// key in a KeyValue pair
  
import java.util.*;
import org.javatuples.KeyValue;
  
class GfG {
    public static void main(String[] args)
    {
        // Creating a KeyValue object
        KeyValue<Integer, String> kv
            = KeyValue.with(Integer.valueOf(1),
                            "A computer science portal");
  
        // Using setKey() method
        KeyValue<String, String> kv1 = kv.setKey("Lazyroar");
  
        // Printing the returned KeyValue
        System.out.println(kv1);
    }
}


Output:

[Lazyroar, A computer science portal]

Example 2:




// Below is a Java program to set
// key in a KeyValue pair
  
import java.util.*;
import org.javatuples.KeyValue;
  
class GfG {
    public static void main(String[] args)
    {
        // Creating a KeyValue object
        KeyValue<Integer, String> kv
            = KeyValue.with(Integer.valueOf(1),
                            "1");
  
        // Using setKey() method
        KeyValue<String, String> kv1 = kv.setKey("One");
  
        // Printing the returned KeyValue
        System.out.println(kv1);
    }
}


Output:

[One, 1]
RELATED ARTICLES

Most Popular

Dominic
32399 POSTS0 COMMENTS
Milvus
95 POSTS0 COMMENTS
Nango Kala
6765 POSTS0 COMMENTS
Nicole Veronica
11917 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11985 POSTS0 COMMENTS
Shaida Kate Naidoo
6890 POSTS0 COMMENTS
Ted Musemwa
7143 POSTS0 COMMENTS
Thapelo Manthata
6838 POSTS0 COMMENTS
Umr Jansen
6840 POSTS0 COMMENTS