Home > Software design >  Arrays.asList() how to append String value to each item
Arrays.asList() how to append String value to each item

Time:05-21

I'm reading getting the names of all the images inside a subfolder of my assets folder.

//Returns name of all the images inside folder_previews

private static List<String> getPreviews(Context context) throws IOException {
        AssetManager assetManager = context.getAssets();
        String[] files = assetManager.list("folder_previews");
        return Arrays.asList(files);
}

I then want to concat a String before each one.

try {
    List<String> imageNames = getPreviews(context);
    String prefix = "file:///android_asset/folder_previews/";

    List<String> formattedImageNames = new ArrayList<>();
    for(String s : imageNames){
       formattedImageNames.add(prefix.concat(s));
    }

} catch (IOException e) {
    e.printStackTrace();
}

Is there a way to do it inside my method getPreviews with Array's .asList() so I can avoid using the loop?

CodePudding user response:

Arrays.asList doesn't allow the creation of Lists from derived items directly.

However, you could use Streams for creating a List from concatenated Strings.

imageNames
    .stream()
    .map(s->prefix.concat(s))//alternative: .map(prefix::concat)
    .toList();

Before Java 16, you would need to use .collect(Collectors.toList()) instead of .toList().

This essentially does the same as your loop. It creates a Stream (a data processing pipeline) from imageNames, maps each name (converts each name) with prefix.concat(s) and collects the result to a List.

Note that you might also want to use the -operator for string concatenation.

CodePudding user response:

Use Stream api to map value to each element only for java 8 and above version

Arrays.stream(files) >> converting string array to stream

.map((elem) -> prefix elem) >> taing each element and returning new modified string .collect(Collectors.toList()) >> collecting to List

 private static List<String> getPreviews(Context context) throws IOException {

    String prefix = "file:///android_asset/folder_previews/";
            AssetManager assetManager = context.getAssets();
            String[] files = assetManager.list("folder_previews");
             List<String> modifiedList = Arrays.stream(files)
                                               .map((elem) -> prefix  elem)
                                               .collect(Collectors.toList());
        return modifiedList ;
    }
  • Related