Skip to content

Instantly share code, notes, and snippets.

@tsabirgaliev
Last active August 25, 2020 06:17
Show Gist options
  • Save tsabirgaliev/dbf5e28868af56b4452df2a1b15735ae to your computer and use it in GitHub Desktop.
Save tsabirgaliev/dbf5e28868af56b4452df2a1b15735ae to your computer and use it in GitHub Desktop.
package org.example;
import org.yaml.snakeyaml.Yaml;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Yaml2Properties {
private static Stream<Map.Entry<String, String>> processEntry(String prefix, Object o) {
if (o instanceof ArrayList) {
ArrayList list = (ArrayList) o;
return IntStream.range(0, list.size())
.boxed()
.flatMap(i -> processEntry(prefix + "." + i, list.get(i)));
} else if (o instanceof Map) {
Map<String, ?> map = (Map) o;
return map.entrySet()
.stream()
.flatMap(entry -> processEntry(prefix + "." + entry.getKey(), entry.getValue()));
} else {
String value = String.valueOf(o);
return Stream.of(new AbstractMap.SimpleEntry<>(prefix, value));
}
}
public static Properties yaml2props(Map<String, ?> map) {
Stream<Map.Entry<String, String>> stream = map.entrySet()
.stream()
.flatMap(entry -> processEntry(entry.getKey(), entry.getValue()));
Properties result = new Properties();
stream.forEach(entry -> result.setProperty(entry.getKey(), entry.getValue()));
return result;
}
public static void main(String[] args) {
Yaml yaml = new Yaml();
Map<String, ?> map = yaml.load(Yaml2Properties.class.getResourceAsStream("/test.yaml"));
Properties props = yaml2props(map);
props.list(System.out);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment