HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Google Gson - adding arrays to a List

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraysgooglegsonaddinglist

Problem

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

List list = new ArrayList();
    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"
]
]

Solution

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

List 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

Code Snippets

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

Context

StackExchange Code Review Q#113934, answer score: 4

Revisions (0)

No revisions yet.