Java 如何从 LinkedHashMap 迭代器获取键值对?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18900082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:09:03  来源:igfitidea点击:

How I can get key, value pair from LinkedHashMap iterator?

javaiteratorlinkedhashmap

提问by Borneq

I test SnakeYAML library to read .yaml documents. I have read Example 2.27. Invoice from http://yaml.org/spec/1.1/and I get object:

我测试 SnakeYAML 库以读取 .yaml 文档。我已经阅读了示例 2.27。来自http://yaml.org/spec/1.1/ 的发票,我得到了对象:

System.out.println(content);
Yaml yaml = new Yaml();
Object o = yaml.load(content);

where content is String loaded from file using Files.readAllBytes, encoding.decode (encoding is StandardCharsets.UTF_8)

其中内容是使用 Files.readAllBytes, encoding.decode 从文件加载的字符串(编码是 StandardCharsets.UTF_8)

Reflection gaves me that o is type of java.util.LinkedHashMap and I can iterate over them:

反射告诉我 o 是 java.util.LinkedHashMap 的类型,我可以遍历它们:

Set entrySet = o.entrySet();
Iterator it = entrySet.iterator();
System.out.println("LinkedHashMap entries : ");
while (it.hasNext())
{
    Object entry = it.next();
    System.out.println(entry);
}

Reflection return that type of entry is LinkedHashMap$Entry. But is problem: internal class LinkedHashMap$Entry is private and I can't declare objects this type. How I can get pair from entry, iterator or entrSet?

反射返回该条目类型为 LinkedHashMap$Entry。但问题是:内部类 LinkedHashMap$Entry 是私有的,我不能声明这种类型的对象。我如何从条目、迭代器或 entrSet 中获取配对?

回答by Boris the Spider

You should declare a Map.Entryrather than the LinkedHashMap.Entry:

您应该声明 aMap.Entry而不是LinkedHashMap.Entry

while (it.hasNext())
{
    Map.Entry<?,?> entry = it.next();
    System.out.println(entry.getKey());
    System.out.println(entry.getValue());
}

Map.Entryis the public interface, LinkedHashMap.Entryis a private implementation of that interface.

Map.Entrypublic interface,LinkedHashMap.Entry是该接口的私有实现。

Notice that I also declare the Entrywith <?,?>, this is a generic declaration. If you know the type of the Mapyou can declare that type and you won't need to cast:

请注意,我还声明了Entrywith <?,?>,这是一个通用声明。如果您知道 的类型,则Map可以声明该类型并且不需要强制转换:

Set<Entry<?,?>> entrySet = o.entrySet();
Iterator<Entry<?,?>> it = entrySet.iterator();

Further you can use an enhanced foreach loop to iterate:

此外,您可以使用增强的 foreach 循环进行迭代:

final Map<?,?> myMap = (Map<?,?>) yaml.load(content);
for(final Entry<?,?> entry : o.entrySet()) {
    //do stuff with entry
}

Obviously if you know your Mapis mapping Stringto Object(for example) you could use Map<String, Object>

显然,如果您知道您Map要映射StringObject(例如),您可以使用Map<String, Object>

回答by Trey Jonn