A KeyValuePair in Java
In Java, a KeyValuePair is a data structure that represents a pair of keys and values, similar to a Map.
In Java, a KeyValuePair represents a single key-value entry, unlike a Map which is a collection of multiple entries. It is a simple way to store data as a key-value pair.
Here is an example of a KeyValuePair class in Java:
import java.util.Objects;
public class KeyValuePair<K, V> {
private K key;
private V value;
public KeyValuePair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
KeyValuePair<?, ?> that = (KeyValuePair<?, ?>) o;
return Objects.equals(key, that.key) && Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
}You can use the KeyValuePair class like this:
KeyValuePair<String, Integer> pair = new KeyValuePair<>("key", 10);
String key = pair.getKey();
int value = pair.getValue();Note that Java does not have a built-in KeyValuePair class. You can define your own as shown above, or use standard alternatives like javafx.util.Pair or org.apache.commons.lang3.tuple.Pair from Apache Commons Lang.