5
\$\begingroup\$

I want to make sure if it's good. Maybe there is another better solution.

List<String[]> list = new ArrayList<String[]>();
 for (int i = 0; i < 3; i++) {
 String[] arr = { String.valueOf(i) };
 list.add(arr);
 }
 String json = new Gson().toJson(list);
 System.out.println(json);

Expected output:

[
[
"0"
],
[
"1"
],
[
"2"
]
]
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Dec 14, 2015 at 17:47
\$\endgroup\$
1
  • \$\begingroup\$ Please give a brief explanation of the purpose of the code in the question. Even quoting verbatim is ok (if the licence allows it) \$\endgroup\$ Commented Dec 14, 2015 at 18:48

1 Answer 1

4
\$\begingroup\$

If you are able to use Java 8 you can use streams:

List<String[]> list = IntStream.range(0, 3)
 .mapToObj(i -> new String[] { String.valueOf(i) })
 .collect(Collectors.toList());

Let's break it down:

  • IntStream.range(0, 3) gives you the values 0, 1 and 2
  • .mapToObj(i -> new String[] { String.valueOf(i) }) converts them to a string and puts them into a String[]
  • .collect(Collectors.toList()) collects the stream into a List<String[]>
answered Dec 14, 2015 at 17:57
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.