Pawan
Pawan

Reputation: 32321

How to create a HashMap in java based on the order of HashSet

I have got a LinkedHashMap , and want to create a new LinkedHashMap based on entries present under HashSet

import java.util.*;

public class LinkedHashMapDemo {

    public static void main(String args[]) {
       // Currently empty
        LinkedHashMap<String, String> newhashmap = new LinkedHashMap<String, String>();

        // old hash map
        LinkedHashMap<String, String> oldhashmap = new LinkedHashMap<String, String>();

        // Put elements to the map
        oldhashmap.put("Zara", "zaravalue");
        oldhashmap.put("Mahnaz", "Mahnazvalue");
        oldhashmap.put("Ayan", "Ayanvalue");
        oldhashmap.put("Daisy", "Daisyvalue");
        oldhashmap.put("Qadir", "Qadirvalue");

        HashSet<String> hs = new HashSet<String>();

        // add elements to the hash set
        hs.add("Zara");
        hs.add("Ayan");
        hs.add("Qadir");

        Iterator iterator = hs.iterator();
        while (iterator.hasNext()) {
            String key = (String) iterator.next();
            String val = oldhashmap.get(key);
        }
    }
}

So that the new newhashmap looks as

newhashmap.put("Zara", "Zaravalue");
newhashmap.put("Ayan", "Ayanvalue");
newhashmap.put("Qadir", "Qadirvalue");
newhashmap.put("Mahnaz", "Mahnazvalue");
newhashmap.put("Daisy", "Daisyvalue");

please let me know if this possible

Upvotes: 0

Views: 78

Answers (2)

ELO8C8
ELO8C8

Reputation: 92

My first approach would look like this:

...
LinkedHashMap<String, String> storage = new LinkedHashMap<String, String>();

while (iterator.hasNext()) {
    String key = (String) iterator.next();
    String val = oldhashmap.get(key);
    if(hs.contains(val){
        newhashmap.put(key, val);
    }else {
        storage.put(key, val);
    }
}
newhashmap.putAll(storage);
...

This way you can avoid modifying the old hashmap or iterating through the data twice.

Upvotes: 1

Eddie Curtis
Eddie Curtis

Reputation: 1237

You could use the remove() method if you are willing to remove from the old HashSet

while (iterator.hasNext()) {
    String key = (String) iterator.next();
    String val = oldhashmap.remove(key);
    newhashmap.put(key, val);
}
newhashmap.putAll(oldhashmap);

You might also want to look at creating a TreeMap with a custom Comparator using the order you desire, but this might be a little over-complicated for your example.

Edit: You will also need to change your HashSet to a LinkedHashSet so that you can rely on ordering.

Upvotes: 2

Related Questions