1

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:

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)

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

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?

Borneq
  • 261
  • 1
  • 6
  • 13

2 Answers2

6

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

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

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

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

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

Further you can use an enhanced foreach loop to iterate:

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

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

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
1

Check out the examples posted at: Java - The LinkedHashMap Class and How do I get a keyIterator for a LinkedHashMap?

Community
  • 1
  • 1
Trey Jonn
  • 350
  • 3
  • 17