Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))//altermative: .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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading