Merge Two Android Hash Cards

I want to combine two HashMaps.

I could use map1.putAll (map2); but I do not want to rewrite the key, as they will have conflicting keys.

Thus, the keys on each map will be as

word1     word1
word2     word2
word3     word3

and when I combine them, I would like to:

word1
word2
word3
word4
word5
word6

It can simply overwrite keys, since the keys are incremental and use the first key text, that is, it reads one of the pairs and extracts the word "word", so everyone will be word1 word2.

But another caution I was thinking about the mobile environment and what I can do without having to load the download screen, or even capable.

So, as a starter, I suppose:

    HashMap<String, Object> hm1 = new HashMap<String, Object>();
    hm1.put("key1", "a");
    hm1.put("key2", "a");
    hm1.put("key3", "a");
    HashMap<String, Object> hm2 = new HashMap<String, Object>();
    hm2.put("key1", "1");
    hm2.put("key2", "2");
    hm2.put("key3", "3");

    HashMap<String, Object> newHM = new HashMap<String, Object>();      
    String keyWord = "";
    for (String  s: hm1.keySet()) {
        keyWord = s;
        break;
    }
    int count = 0;
    for (Object o : hm1.values()) {
        newHM.put(keyWord+count, o);
    }
    for (Object o : hm2.values()) {
        newHM.put(keyWord+count, o);
    }

But I wonder how effective it is? Does this look right, and is there a better way to do this? I do not want to use an extra object unnecessarily

+3
2

, , List.

List, .

class KeyWordedArrayList<T> extends ArrayList<T>{
    private final String keyword;

    public KeyWordedArrayList(String keyword){
        this.keyword = keyword;
    }

    public String getKeyword(){
        return keyword;
    }
}

Map:

class KeyWordedMap<T> extends HashMap<Integer, T> {
    private final String keyword;

    public KeyWordedMap(String keyword) {
        this.keyword = keyword;
    }

    public String getKeyword() {
        return keyword;
    }

    @Override
    public void putAll(Map<? extends Integer, ? extends T> m) {
        for (Map.Entry<? extends Integer, ? extends T> entry : m.entrySet()) {
            int i = entry.getKey();
            while (this.containsKey(i)) {
                i++;
            }
            this.put(i, entry.getValue());
        }
    }
}
+2

:

@Override
public void putAll(Map<? extends String, ? extends Object> m) {
    for (Map.Entry<? extends String, ? extends Object> entry : m.entrySet()) {
        String keyWord = "";
        for (String  s: this.keySet()) {
          keyWord = s.substring(0, s.length()-1);
          break;
        }
        int i = 0;
        while (this.containsKey(i)) {
            i++;
        }
        this.put(keyWord +i, entry.getValue());
    }
}
0

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


All Articles