'How to convert List<Integer> into JSONArray of Integers, using stream() method in Java

I'm trying to find best way to convert List of Integers to JSONArray of org.json.JSONArray library for API call. For that purpose I'm trying to implement stream() methods of Java 8.

Given

List<Integer> ids = new ArrayList<>();

ids.add(1);

ids.add(2);

ids.add(3);

Needed JSONArray object

JSONArray ids = [1,2,3]

with using stream() method in Java.



Solution 1:[1]

You can do it easily without using streams by using the constructor of the JSONArray class which accepts a Collection:

List<Integer> ids = List.of(1, 2, 3);
JSONArray json = new JSONArray(ids);

If you have to use streams for some reason:

List<Integer> ids = List.of(1, 2, 3);
JSONArray json = new JSONArray();
ids.stream().forEach(json::put);

As pointed out by Alexander Ivanchenko in the comments however, you should avoid doing this.

Solution 2:[2]

You can use mutable reduction with collect().

Note, that usage of streams is justifiable only if you need to filter or change some values along the way, otherwise it'll be an unnecessary complication of the code.

List<String> source = List.of("1", "2", "3");

JSONArray result =
    source.stream()
          .map(str -> str.concat(".0"))
          .collect(
              JSONArray::new,
              JSONArray::put,
              JSONArray::putAll);
    
System.out.println(result);

Output

["1.0","2.0","3.0"]

Solution 3:[3]

Naive solution: A naive solution is to iterate over the given set and copy each encountered element in the Integer array one by one.

Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
Integer[] array = new Integer[set.size()];
 
int k = 0;
for (Integer i: set) {
    array[k++] = i;
}
 
System.out.println(Arrays.toString(array));

Using Set.toArray() method: Set interface provides the toArray() method that returns an Object array containing the elements of the set.

Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
Object[] array = set.toArray();
System.out.println(Arrays.toString(array));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 fatih