yamlbeans icon indicating copy to clipboard operation
yamlbeans copied to clipboard

Allow duplicate keys in yaml.

Open Dhivyaa21 opened this issue 7 years ago • 4 comments

Can yamlreader append the values duplicate keys to the map instead of overwriting them?

Dhivyaa21 avatar Nov 22 '18 13:11 Dhivyaa21

Maps by definition have unique keys.

NathanSweet avatar Nov 22 '18 14:11 NathanSweet

You want multiple values to use an ArrayList as the map value? You could use a Map implementation that does this. Or you could fork YamlBeans to do this.

NathanSweet avatar Nov 22 '18 14:11 NathanSweet

Yeah.. By default a hashmap ignores duplicate keys and overwrites the value with the latest one. But my requirement is to allow dupicate keys and append its values like a MultiValuedMap. Can YamlBeans do this?

Dhivyaa21 avatar Nov 22 '18 14:11 Dhivyaa21

@Dhivyaa21 @NathanSweet

  • Default
String yaml = "key: 001\nkey: 002";
YamlReader reader = new YamlReader(yaml);
Object object = reader.read();

object is a HashMap instance, does not support duplicate keys.

  • Specified type
String yaml = "key: 001\nkey: 002";
YamlReader reader = new YamlReader(yaml);
ArrayListValuedHashMap<String, String> arrayListValuedHashMap = 
reader.read(ArrayListValuedHashMap.class);

Deserialization exception, yamlbeans does not support.

  • Can use YamlDocumentReader
String yaml = "key: 001\nkey: 002";
YamlDocumentReader yamlDocumentReader = new YamlDocumentReader(yaml);
YamlDocument yamlDocument = yamlDocumentReader.read();

YamlEntry entry1 = yamlDocument.getEntry(0);
System.out.println("key: " + entry1.getKey() + ", value: " + entry1.getValue());
YamlEntry entry2 = yamlDocument.getEntry(1);
System.out.println("key: " + entry2.getKey() + ", value: " + entry2.getValue());

Console:

key: key, value: 001
key: key, value: 002

Mr14huashao avatar Jun 09 '20 03:06 Mr14huashao