How to create a pair of values within a Map in Java

3

Is it possible to create a Map in Java using the concept of pair that exists in C ++? I have tried using the form below, however, I can not assign values to my map.

Map<String, Entry<Entry<Integer,Integer>,String> > sub = new HashMap<>();

How can I resolve this?

    
asked by anonymous 04.04.2015 / 21:46

1 answer

3

Java does not actually have a Pair itself.

You can implement your own class that handles the desired data pair. Usually this class is an implementation of the Map.Entry<K,V> interface. An example implementation can be seen in this answer 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;
    }
}

Of course nothing prevents you from creating a class that implements the pair as you wish without implementing this interface.

Or you can use AbstractMap.SimpleEntry<K,V> . It could use like this:

Map<String, Map.Entry<Map.Entry<Integer, Integer>, String>> sub = new HashMap<>();

You would have to create each object of these, go nestling 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);
    
04.04.2015 / 22:09