Converting array string to arraylist without nesting it in Java

I’m not sure if I understand the problem correctly, but taking the signature of the sample function at face value, some quick and dirty solution may be as follows. Of course, all these maps could be collapsed into one iteration only.

public class Main {

    public static void main(String[] args) {
        String s = "[\"filename1.png\", \"filename2.png\", \"filename3.png\"]";
        List<String> attachments = splitAttachmentFilenames(s);

        attachments.forEach(System.out::println);
    }


    static List<String> splitAttachmentFilenames(String attachment) {
        // attachment: ["filename.png", "filename.png"]
        String[] arr = attachment.split(",");
        List<String> l = Arrays.asList(arr);

        return l.stream()
                .map(String::trim)
                .map(s -> removeLeadingChar(s, '['))
                .map(s -> removeTrailingChar(s, ']'))
                .map(s -> removeLeadingChar(s, '"'))
                .map(s -> removeTrailingChar(s, '"'))
                .collect(Collectors.toList());
    }

    static String removeLeadingChar(String s, char c) {
        StringBuilder sb = new StringBuilder(s);
        while (sb.length() > 1 && sb.charAt(0) == c) {
            sb.deleteCharAt(0);
        }
        return sb.toString();
    }

    static String removeTrailingChar(String s, char c) {
        StringBuilder sb = new StringBuilder(s);
        while (sb.length() > 1 && sb.charAt(sb.length() - 1) == c) {
            sb.setLength(sb.length() - 1);
        }
        return sb.toString();
    }
}

Leave a Comment