Double key value pairs

Is there a built-in data structure in java that takes pairs of key values ​​and allows duplication? I create a checklist of characters in a string, but some characters occur multiple times.

ex

j -> false
a -> false
v -> false
a -> false
+4
source share
5 answers

You can simulate several key-value (KV) pairs by storing a list of values ​​for each on the map. This is the standard implementation approach for multi-valued cards.

So, if the key is an object Characterand the value Boolean, you can do

Map<Character, List<Boolean>> multimap = new Map<Character, List<Boolean>>();

and every time you want to add a new value to an existing KV pair on the map, just call

multimap.get(key).add(value);

key - value Boolean.

Guava Google ( ) Multimap, , a MultiMap<Character, Boolean> . , Apache Commons Collections MultiValueMap. fooobar.com/questions/754805/... .

, List Set.

+3

List Pair s:

public class Pair<T, U> {
    public final T key;
    public final U value;

    public Pair(T key, U value) {
        this.key = key;
        this.value = value;
    }
}

public class YourApp {
    public static void main(String[] args) {
        List<Pair<Character, Boolean>> charList = new ArrayList<Pair<Character, Boolean>>();
        charList.add(new Pair('j', false));
        charList.add(new Pair('a', false));
        charList.add(new Pair('v', false));
        charList.add(new Pair('a', false));

        for (Pair<Character, Boolean> pair : charList) {
            System.out.println(pair.key + " -> " + pair.value);
        }
    }
}

Pair , . List, .

+3

MultiMap<Character,Boolean> bcoz, , org.apache.commons.collections.

ArrayList Class, char boolean pair.

+3

, .

- ArrayList , char/boolean , .

+2

commons.apache.org MultiHashMap. ...!!!

MultiHashMap mp = new MultiHashMap();
mp.put("a", "1");
mp.put("b", "4");
mp.put("c", "2");
mp.put("a", "6");
List list = null;
Set set = mp.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
        Map.Entry<String, List<String>> me = (Map.Entry) i.next();
        for(int j = 0 ; j< me.getValue().size(); j++ ){
        System.out.println(me.getKey() +" : " +me.getValue().get(j));
        }
    }
}
+1

Source: https://habr.com/ru/post/1525483/


All Articles