Skip to content
Advertisement

Arrays.asList() how to append String value to each item

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement