Search code examples
javastring.format

Format text with a list of argument in java


I have a sting with multiple %s for string formatting. And i have an array of strings which are supposed to be arguments for string formatting. Like this

List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
String toFormat =  "This is a first value %s, This is a second value %s"
String result = String.formant (toFormat, list.get(0), list.get(1));

But it doesn't look good with a number of element greater than 2. How can i format a string without picking each argument from list individually?


Solution

  • String.format() take as parameters a format and array of Objects (vararg is an array of Objects behind the scene). All you need to do is to convert your list to array of Strings and pass that to String.format(), like so:

    public static void main(String args[]) {
        List<String> list = new ArrayList<>();
        list.add("A");
        list.add("B");
        String toFormat =  "This is a first value %s, This is a second value %s";
        String result = String.format (toFormat, list.toArray(new String[0]));
        System.out.println(result);
    }