3

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());

}
2
  • Can you add more details to the problem, like what you have tried so far. Commented Oct 16, 2019 at 11:56
  • @JennisVaishnav please check again I renewed the topic Commented Oct 16, 2019 at 11:57

3 Answers 3

4

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

Comments

1

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);

Comments

1

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());

3 Comments

Q1, Q2 is manually appended there, the index of the question.
The number 1,2,3 in the with Q intuitively could be the index of the question.
Yes, it is. But there are individual getters for each of the 10 questions anyways. If OP wants to hardcode the String, this is the syntactically correct way to pass a list of values to a varargs method.

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.