将ArrayList转换为HashMap <string,string =“”>

时间:2015-08-04 07:30:35

标签: java android arraylist

我有ArrayList

public ArrayList<HashMap<String, String>> xmlFileNames = new ArrayList<>();

我希望将其转换为:

HashMap<String, String> comparemap2 = new HashMap<>();

我想要的是:我想要ArrayList中的所有Items并希望将它们放入HashMap中 我的HashMap看起来像:

  

关键值

     

job_id 032014091029309130921.xml

     

job_id 201302149014021492929.xml

     

job_id 203921904901920952099.xml

修改 稍后我想将此地图与现有地图进行比较:

Properties properties = new Properties();
            try {
                properties.load(openFileInput("comparexml.kx_todo"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            for (String key : properties.stringPropertyNames()) {
                compareMap.put(key, properties.get(key).toString());
            }
HashMap<String, String> oldCompareMap = new HashMap<>();
            for (HashMap key : xmlFileNames) {
                oldCompareMap.putAll(key);
            }
            isEqualMaps(oldCompareMap, compareMap);

如果compareMap中存在文件名,我只想比较一下。如果没有,请将其添加到xmlFileName地图

我在StackOverFlow中查找,如何将ArrayList转换为HashMap。但其他线程会处理ItemProduct等数据类型。

我希望你能帮助我!

亲切的问候

4 个答案:

答案 0 :(得分:8)

...鉴于

public ArrayList<HashMap<String, String>> xmlFileNames = new ArrayList<>();

然后这样的事情应该做到。

HashMap<String, String> nhm = new HashMap<>();
for (HashMap xmlFileHm : xmlFileNames ) {
  nhm.putAll(xmlFileHm);
}

但请注意,如果您的哈希图中有重复的密钥,它们将被覆盖。

您还应该考虑对接口进行编码。查看Map和List,而不是将集合键入实现(ArrayList和HashMap)。看看这个非常有趣的帖子What does it mean to "program to an interface"?

根据您尝试做的事情,您可以考虑使用MultiMap,因为这可能更好地为您的目的服务

修改更新问题后......

使用一个键和多个值,多图在这里会更好。虽然可以说密钥永远不会改变,但您可以将值存储在列表中。对于多功能放大器,您可以使用Google的番石榴库或自己动手做。例如(没有检查编译错误,因为我从头开始这样做)

Map<String, List<String>> m = new HashMap<>();
if (m.containsKey("key")) {
   m.get("key").add("new value");
}
else {
  List<String> l = new ArrayList<>();
  l.add("new value");
  m.put("key", l);
}

答案 1 :(得分:3)

您可以创建一个新的HashMap,然后遍历列表并将地图中的所有元素从列表中放入主地图。

List<Map<String, String>> list = new ArrayList<>();
Map<String, String> map = new HashMap<>();
for (Map<String, String> mapFromList : list) {
    map.putAll(mapFromList);
}

答案 2 :(得分:3)

你可以尝试这样的事情......

ArrayList<HashMap<String, String>> xmlFileNames = new ArrayList<>();
HashMap<String, String> comparemap2 = new HashMap<>();
for(HashMap<String, String> i:xmlFileNames){
     comparemap2.putAll(i);
}

您可能需要考虑重复键的情况。否则他们会被覆盖。

答案 3 :(得分:1)

创建一个新地图并将所有arrayList的元素放到地图上。

但是在这种情况下,如果你在arrayList(hashmap)的两个元素中有相同的键,那么它将覆盖前一个。