Java doesn’t really have one Pair
proper.
You can implement your own class that handles the desired data pair. Normally this class is an interface implementation Map.Entry<K,V>
. An example of implementation can be seen in that reply in the OS:
import java.util.Map;
final class MyEntry<K, V> implements Map.Entry<K, V> {
private final K key;
private V value;
public MyEntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
V old = this.value;
this.value = value;
return old;
}
}
I put in the Github for future reference.
Of course nothing prevents you from creating a class that implements the pair as you wish without implementing this interface.
Or you can use the AbstractMap.SimpleEntry<K,V>
. Could use it like this:
Map<String, Map.Entry<Map.Entry<Integer, Integer>, String>> sub = new HashMap<>();
You would have to create each object of these, go nesting to put on the map:
Map.Entry<Integer, Integer> par1 = new AbstractMap.SimpleEntry<>(0, 1);
Map.Entry<Map.Entry<Integer, Integer>, String> par2 = new AbstractMap.SimpleEntry<>(par1, "txt");
sub.put("chave", par2);
Incredible as it may seem, to this day there is no generic data structure in Java capable of storing a pair of values... >:( But second that answer in Soen it is possible to use
Map.Entry
for this purpose - you just instantiate one of its concrete implementations (AbstractMap.SimpleEntry
orAbstractMap.SimpleImmutableEntry
) instead of the interface itself. A perhaps more user friendly option (if available) is thejavafx.util.Pair
– mgibsonbr
Good idea @mgibsonbr! Mto thanks!!
– Duds