0

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'
6
  • 1
    test.add("'A'"); Commented Jul 13, 2022 at 10:19
  • test.stream().collect(Collectors.joining("','", "'", "'")) Commented Jul 13, 2022 at 10:20
  • System.out.println(String.format("'%s'", String.join("','", test))); Commented Jul 13, 2022 at 10:25
  • @deHaar – If you do not post your comment as an answer, I will do it – and grab the reputation for it! 😉 Commented Jul 13, 2022 at 10:28
  • @tquadrat answer posted, let's see what happens ;-) Commented Jul 13, 2022 at 10:47

2 Answers 2

7

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));
Sign up to request clarification or add additional context in comments.

3 Comments

The second option can be written shorter: var formatted = "'%s'".formatted( String.join( "','", test ) );– The generated code should be the same./And I upvoted your answer! 😉
Thanks, @tquadrat, but which Java version is needed for the shorter version?
String::formatted came with Java 15, and var came with Java 10. Current version is Java 17 LTS, or Java 18 (or do we have already Java 19? – I use only the LTS versions if possible …)
1

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 deHaar'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("','", "'", "'"));
        }
    };
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.