0

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());
        }
2
  • 1
    Why would you expect your map value to be of type String when the map is declared as Map<String, String[]>>? Commented Sep 24, 2021 at 3:25
  • 1
    Smells like you should have a typed data structure. Commented Sep 24, 2021 at 3:32

2 Answers 2

0

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);

     });
}
Sign up to request clarification or add additional context in comments.

Comments

0

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());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.