简体   繁体   中英

how to add list elements corresponding to key in Hashmap?

I want to add list elements to corresponding keys but the problem I am facing is that values which are added already to different key is also added.

for every iteration I am adding key and values

like 1st iteration:
Hashmap added {A=[1,2]}

2nd iteration
Hashmap added {A=[1,2,3,4]} ---- here I don't want to add 1,2-only new elements should be added

expected here is {A=[3,4]}

Map<String, List<String>> country_hashmap = new HashMap<String, List<String>>();

Map<String, List<String>> country_hashmaperor = new HashMap<String, List<String>>();
List<String> warningJsinList = new ArrayList<>();
List<String> errorList = new ArrayList<>();
for(int i =0;i<totalMessages;i++){

    int totalMessageperElement = 5;
    for(int j =0;j<totalMessageperElement;j++){


    if(severityValue.equalsIgnoreCase("Warning")){
        warningJsinList.add(message[i]).toString().replace("[", "").replace("]", "").replace("\"", ""));


        if(!(j + 1 < totalMessageperElement)) {
            country_hashmap.put(elementkey, warningJsinList);
        }
    }
    else{
        errorList.add(message[i]).toString().replace("[", "").replace("]", "").replace("\"", ""));
        if(!(j + 1 < totalMessageperElement)) {
              country_hashmaperor.put(elementkey, errorList);      
        }
    }
}

Remove the lines with System.out.{print,println} , I've only added just to illustrate the functionality:

public class App {
    public static void main(String[] args) {
        Map<String, List<String>> map = new HashMap<>();
        add(map, "A", Stream.of("1", "2").collect(toList()));
        add(map, "A", Stream.of("1", "2", "3", "4").collect(toList()));
        add(map, "A", Stream.of("4", "5", "6").collect(toList()));
    }

    private static void add(Map<String, List<String>> map, String key, List<String> newValues) {
        System.out.print("Map before: " + map + ", adding: " + newValues + " for key " + key);
        List<String> oldValues = map.getOrDefault(key, new ArrayList<>());
        newValues.removeAll(oldValues);
        map.put(key, newValues);
        System.out.println(", map after: " + map);
    }
}

Output:

Map before: {}, adding: [1, 2] for key A, map after: {A=[1, 2]}
Map before: {A=[1, 2]}, adding: [1, 2, 3, 4] for key A, map after: {A=[3, 4]}
Map before: {A=[3, 4]}, adding: [4, 5, 6] for key A, map after: {A=[5, 6]}

Not recommended, but if you're certain that you need a data structure that's XORing (remove if existing, add if missing), you could do this:

static class XorList<T> extends ArrayList<T> {

    @Override
    public boolean addAll(Collection<? extends T> c) {
        c.forEach(this::add);
        return true;
    }

    @Override
    public boolean add(T t) {
        return this.contains(t) ? this.remove(t) : super.add(t);
    }
}

Map<String, XorList<String>> map1 = new HashMap<>();
map1.computeIfAbsent("A", (key) -> new XorList<>()).addAll(Stream.of("1", "2").collect(toList()));
System.out.println(map1);
map1.computeIfAbsent("A", (key) -> new XorList<>()).addAll(Stream.of("1", "2", "3", "4").collect(toList()));
System.out.println(map1);
map1.computeIfAbsent("A", (key) -> new XorList<>()).addAll(Stream.of("4", "5", "6").collect(toList()));
System.out.println(map1);

Output for this one is:

{A=[1, 2]}
{A=[3, 4]}
{A=[3, 5, 6]}

By the way, you probably need to use a Set instead of List , isn't it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM