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

Time:05-07

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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"]
  • Related