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("','", "'", "'"));
}
};
}
test.add("'A'");test.stream().collect(Collectors.joining("','", "'", "'"))System.out.println(String.format("'%s'", String.join("','", test)));