How to create a String with String.format by taking parameters from a list

Viewed 232

I want to create a String with String.format like this String.format("Q1={}, Q2={}, Q3={}, Q4={}" list) from the values of a list that contains Integers.

private String createString(Player player){

List<Integer> answers= new ArrayList<>();
    answers.add(player.getQuestion1());
    answers.add(player.getQuestion2());
    answers.add(player.getQuestion3());
    answers.add(player.getQuestion4());
    answers.add(player.getQuestion5());
    answers.add(player.getQuestion6());
    answers.add(player.getQuestion7());
    answers.add(player.getQuestion8());
    answers.add(player.getQuestion9());
    answers.add(player.getQuestion10());
    return String.format("Q1={}, Q2={}, Q3={}, Q4={}, Q5={}, Q6={}, Q7={}, Q8={}, Q9={}, Q10={}", answers.stream().map(a -> a.toString());

}
3 Answers

Something like the following using Collectors.joining with mapping as required witht index and answer :

return IntStream.range(0, answers.size())
            .mapToObj(idx -> String.format("Q%s = %s", idx + 1, answers.get(idx)))
            .collect(Collectors.joining(", "))

String.format is not suitable for formatting a list. Usually, String.join is more suitable.

First, create a list of strings to be joined by commas:

List<String> strings = IntStream.rangeClosed(1, answers.size())
    .mapToObj(x -> "Q" + x + "=" + answers.get(x - 1))
    .collect(Collectors.toList());

Then, call String.join:

String result = String.join(", ", strings);

String.format doesn't work well for this example because you need exactly the amount of placeholders in your format as the list size. You are better off building your own String. But in case you want to stick to String.format:

Since String.format uses varargs (which is an array), you can simply use toArray(). Please note that the placeholders in the format cannot be {} but something like %d, %s and so on

return String.format("Q1=%s, Q2=%s, Q3=%s, Q4=%s, Q5=%s, ...", answers.toArray());
Related