![]() |
VOOZH | about |
A KeyValue is a Tuple from JavaTuples library that deals with only 2 elements - a key and a value. Since this KeyValue is a generic class, it can hold any type of value in it.
Since KeyValue is a Tuple, hence it also has all the characteristics of JavaTuples:
public final class KeyValue<A, B> extends Tuple implements IValueKey<A>, IValueValue<B>
Object ↳ org.javatuples.Tuple ↳ org.javatuples.KeyValue<A, B>
KeyValue<A, B> kv = new KeyValue<A, B>(value1, value2);
Example:
Output:
[1, GeeksforGeeks]
KeyValue<type1, type2> kv = KeyValue.with(value1, value2);
Example:
Output:
[1, GeeksforGeeks]
KeyValue<type1, type2> kv = KeyValue.fromCollection(collectionWith_2_value); KeyValue<type1, type2> kv = KeyValue.fromArray(arrayWith_2_value);
Example:
Output:
[GeeksforGeeks, A computer portal] [GeeksforGeeks, A computer portal]
The getValue() and getKey() methods can be used to fetch the value and key respectively in a KeyValue Tuple.
KeyValue<type1, type2> kv = new KeyValue<type1, type2>(value1, value2); type2 val1 = kv.getKey();
Example:
Output:
1
KeyValue<type1, type2> kv = new KeyValue<type1, type2>(value1, value2); type2 val1 = kv.getValue();
Example:
Output:
GeeksforGeeks
Since the Tuples are immutable, it means that modifying a value at an index is not possible. Hence, JavaTuples offer setKey(value) and setValue(value) which creates a copy of the KeyValue with a new value according to method used, and returns a new KeyValue object.
KeyValue<type1, type2> kv = new KeyValue<type1, type2>(value1, value2); KeyValue<type1, type2> kvNew = kv.setKey(valueNew);
Example:
Output:
[10, GeeksforGeeks]
KeyValue<type1, type2> kv = new KeyValue<type1, type2>(value1, value2); KeyValue<type1, type2> kvNew = kv.setValue(valueNew);
Example:
Output:
[1, A computer science portal]
An element can be searched in a tuple with the pre-defined method contains(). It returns a boolean value whether the value is present or not.
Syntax:
KeyValue<type1, type2> kv = new KeyValue<type1, type2>(value1, value2); boolean res = kv.contains(value2);
Example:
Output:
true false
Since KeyValue implement the Iterable<Object> interface. It means that they can be iterated in the same way as collections or arrays.
Syntax:
KeyValue<type1, type2> kv =
new KeyValue<type1, type2>(value1, value2);
for (Object item : kv) {
...
}
Example:
Output:
1 GeeksforGeeks