繁体   English   中英

遍历Hashmap中的对象

[英]Iterating through object in Hashmap

我需要帮助来尝试遍历对象的Hashmap。 我真的被卡在如何做到这一点。 我尝试检查像这样的链接如何遍历Hashmap中的对象,但仍无法完全按照我的意愿实现。

        List<Object> firstObject = new ArrayList<Object>();
        HashMap<Integer, Object> mapEx = new HashMap<> ();

        /* Put the data to Map*/

        mapEx.put(1, "First");       // String
        mapEx.put(2, 12.01);         // float
        mapEx.put(3, 12345);         // int
        mapEx.put(4, 600851475143L); // Long

        /* add map to firstObject */
        firstObject.add(mapEx);

        HashMap<String, Object> secondMap = new HashMap<> ();
        secondMap.put("mapEx", firstObject);

        Log.d("mapEx: ",secondMap.get("mapEx").toString()); 
        //When i print the line, this is the result below

        D/mapEx:﹕ [{4=600851475143, 1=First, 3=12345, 2=12.01}]

但是我该如何实际遍历它们呢? 这样出来

4=600851475143
1=First
3=12345
2=12.01

并且也可以通过其键来呼叫每个人。

提前致谢。

您链接的示例确实回答了这个问题。 这就是您的情况:

for (Map.Entry<Integer, Object> entry : mapEx.entrySet()) {
    System.out.println(entry.getKey() + "=" + entry.getValue());
}

Java 8流解决方案

mapEx.entrySet().stream().forEach(e ->
    System.out.println(e.getKey() + "=" + e.getValue())
);

这里这里有关HashMaps的教程

对于这里的流

像这样:

for (HashMap<Object, Object> map : firstObject) {
    for (Object key : map.keySet()) {
        Object value = map.get(key);

        System.out.println("key = " + key + " value = " +  value);
    }
}

暂无
暂无

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

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