Home > Blockchain >  Hashmap inside a hashmap not removing the keys using remove?
Hashmap inside a hashmap not removing the keys using remove?

Time:03-25

This is my list.

list = Stream.of(
        "06|20|1",
        "11|20|2",
        "11|20|2",
        "07|207|6",
        "11|207|2",
        "07|207|6",
).collect(Collectors.toList());

I have a hashmap such as:

HashMap<String, HashMap<String, String>> hashMap = new HashMap<>();
HashMap<String, String> newHash = new HashMap<>();

And my code is

for (String line : list) {
    String key, value, priority;
    key = line.split("\\|", -1)[1];
    value = line.split("\\|", -1)[0];
    priority = line.split("\\|", -1)[2];

    if (hashMap.containsKey(key)) {
        HashMap<String, String> getPriority = hashMap.get(key);
        Map.Entry<String, String> entry = getPriority.entrySet().iterator().next();
        String oldKey = entry.getKey();
        String previousPrior = getPriority.get(oldKey);
        if (Integer.parseInt(priority) > Integer.parseInt(previousPrior)) {
            getPriority.remove(oldKey);
            getPriority.put(value,priority);
           hashMap.put(key, getPriority);
        }
    } else {
        newHash.put(value, priority);
        System.out.println(newhas);
        hashMap.put(key, newhas);
    }

}

I want to have the have the key with highest priority only such as:

{20={11=2},207={07=6}}

as 11 and 7 has the highest valaues in 20 and 207.

But i am getting all values in the inner hashmap.

CodePudding user response:

How about using streams instead?

Map<String, Map<String, String>> map = list.stream()
        .map(line -> line.split("\\|"))
        .sorted(Comparator.comparingInt(line -> Integer.parseInt(line[2])))
        .collect(Collectors.toMap(
                line -> line[1],
                line -> Map.of(line[0], line[2]),
                (low, high) -> high));

Ideone Demo

CodePudding user response:

For each new key that you insert in your Map variable in the else condition of your code you need to create new HashMap to insert it along with the new key. What you are doing is using the same newhas variable for all the keys in your Map variable. So change this

        else {
            newhas.put(value, priority);
            System.out.println(newhas);
            Map.put(key, newhas);
        }

to

       else {
            newHas = new HashMap<>();
            newhas.put(value, priority);
            System.out.println(newhas);
            Map.put(key, newhas);
        }

Ideone Demo

  • Related