Skip to content
Advertisement

How to Iterate over a String Array inside .map()

So i have these lines in a method –

private List<String> buildLwaScopePermissionsList(final List<Permission> permissions) {
       return Optional.ofNullable(permissions).orElse(Collections.emptyList())
               .stream()
               .map(Permission::getName)
               .map(Permission.Name::getValues)
               .collect(collectingAndThen(toList(), ImmutableList::copyOf));
   }

where Permission is a class and Name is a static inner class inside Permission Class, and getName() is a non-static method inside Permission class and getValues() is a static method inside Name class. The problem is getValues method returns a String Array. I am not able to pick up 1 by 1 item form the returned values and concatinate with Name and store it in the list.

 public static String[] getValues() {
            return values.clone();
        }

Advertisement

Answer

You can use flatMap to flatten multiple values into one stream.

If you have a single permission, you can get a Stream of the concatenated Names by doing Arrays.stream(Permission.Name.getValues()).map(val -> permission.getName() + val). By using flatMap, you can put all these values into the original Stream:

private List<String> buildLwaScopePermissionsList(final List<Permission> permissions) {
   return Optional.ofNullable(permissions).orElse(Collections.emptyList())
           .stream()
           .flatMap(permission -> Arrays.stream(Permission.Name.getValues()).map(val -> permission.getName() + val))
           .collect(collectingAndThen(toList(), ImmutableList::copyOf));
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement