I have an object of Optional<Map<String,Map<String,String[]>>>
How do I loop over each string in the array?
The below code I am expecting "application" to be 'String' but it gives me 'String[]'
Optional<Map<String,Map<String,String[]>>> myObject = Optional.of(yamlReader.read(name, HashMap.class));
Set<Map.Entry<String, Map<String, String[]>>> abc = myObject.get().entrySet();
for ( Map.Entry<String, Map<String, String[]>> x:abc) {
Map<String, String[]> v = x.getValue();
//I am expecting "application" to be String here but it is an array of Strings for some reason
for (String[] application: v.values()) {
System.out.println(application " " x.getKey());
}
CodePudding user response:
You need to iterate through the String[]
to get individual values.
May be you might need to verify the given requirement with structure you are using now.
for (Map.Entry<String, Map<String, String[]>> x : abc) {
Map<String, String[]> v = x.getValue();
v.values().forEach(value -> {
System.out.println("value:" " " value);
});
}
CodePudding user response:
it is an array of String because v.values()
is Collection<String[]>, it is not just String. if you want to print only String, you would need to flat that out.
So if you end goal is to just print all Strings available in your collection, you can use below code.
myObject.ifPresent(map -> map.values().stream().map(Map::values).flatMap(Collection::stream).flatMap(Arrays::stream).forEach(System.out::println));
or if you would like to tweak your code, do something like below to replace your for last loop
v.values().stream().flatMap(Arrays::stream).forEach(application -> System.out.println(application " " x.getKey()));
OR
for (String[] application: v.values()) {
System.out.println(Arrays.asList(application) " " x.getKey());
}