简体   繁体   English

如何基于HashSet的顺序在Java中创建HashMap

[英]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 我有一个LinkedHashMap,并想基于HashSet下的条目创建一个新的LinkedHashMap

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看起来就像

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 请让我知道是否可能

You could use the remove() method if you are willing to remove from the old HashSet 如果您愿意从旧的HashSet中删除,则可以使用remove()方法。

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. 您可能还想查看使用所需顺序使用自定义Comparator创建TreeMap的方法,但是对于您的示例而言,这可能有些复杂。

Edit: You will also need to change your HashSet to a LinkedHashSet so that you can rely on ordering. 编辑:您还需要将HashSet更改为LinkedHashSet,以便可以依赖排序。

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. 这样,您可以避免修改旧的哈希图或对数据进行两次迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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