Home > Software design >  Split Java List items within String
Split Java List items within String

Time:07-14

The code example below shows a Test class that is supposed to print the list out as follows:

'A','B','C' (note the quotation marks).

Is there a method I can use to do that kind of formatting directly within the String assignment?

public class TEST {
    public static void main(String[] args) {

        List<String> test = new ArrayList<>();
        test.add("A");
        test.add("B");
        test.add("C");

        System.out.println(test);

        System.out.println("Expected: 'A','B','C'"); // wanted output

    }
}

Output:

[A, B, C]
Expected: 'A','B','C'

CodePudding user response:

One option to print the desired result would be to use String.join in System.out.format:

public static void main(String[] args) {
    List<String> test = new ArrayList<>();
    test.add("A");
    test.add("B");
    test.add("C");
    
    System.out.format("'%s'", String.join("','", test));
}

This code produces the following output:

'A','B','C'

Applying this format directly within the String assignment can be done in a similar way, by combining String.format and String.join:

String formatted = String.format("'%s'", String.join("','", test));

CodePudding user response:

You can use any of a variety of methods to do the conversion. You can then use your favorite method in a lambda like so. Here I am using deHarr's solution.

Function<List<String>, String> format = lst-> String.format("'%s'", 
                String.join("','", lst));

String result = format.apply(myList);

A somewhat more extreme solution is to create a method that returns an ArrayList with the toString method overridden. Unless you create a lot of lists of varying types and don't want to have to reformat the list, it is probably overkill. But it demonstrates a technique.

List<String> listString = createList(List.of("A","B","C"));
List<Integer> listInt = createList(List.of(1,2,3,4));
System.out.println(listString);
System.out.println(listInt);

prints

'A','B','C'
'1','2','3','4'

A single no arg method could be used and then the list populated. I added a helper to permit passing a Collection to populate the list upon creation.

  • the no arg method calls the the other with an empty list.
  • the single arg method simply returns an instance of the ArrayList with populated with the supplied collection and overriding the toString() method.
@SuppressWarnings("unchecked")
public static <T> List<T> createList() {
    return createList(Collections.EMPTY_LIST);
}
    
public static <T> List<T> createList(Collection<T> list) {
    return new ArrayList<T>(list) {
        @Override
        public String toString() {
            return stream().map(s -> s   "")
                    .collect(Collectors.joining("','", "'", "'"));
        }
    };
}
  • Related