Convert int[] to List and Back Using Streams

Author: Tatyana Milkina
  1. int[] Array → List<Integer> Collection
  2. List<Integer> Collection → int[] Array
  3. Alternative: Manual Conversion Without Stream API
  4. Why List<int> Is Not Allowed
  5. Conclusion

Working with arrays and collections is a fundamental part of Java development. But they have different characteristics:

Arrays are fixed-length structures.

Collections (List, Set, etc.) are flexible containers that allow easy adding, removing, and filtering of data.

It's a common task to convert an int[] array to a List<Integer> and back. Below is how it's done using the Stream API.

1. int[] Array → List<Integer> Collection

int[] numbers = {1, 2, 3, 4, 5};

List<Integer> list = Arrays.stream(numbers) // convert to IntStream
                           .boxed()         // box primitives to Integer
                           .collect(Collectors.toList());

System.out.println(list); // [1, 2, 3, 4, 5]

The boxed() method converts the primitive IntStream into a stream of objects Stream<Integer>, which we then collect into a list using collect(Collectors.toList()).

2. List<Integer> Collection → int[] Array

List<Integer> list = Arrays.asList(10, 20, 30, 40);

int[] array = list.stream()
                  .mapToInt(Integer::intValue)
                  .toArray();

System.out.println(Arrays.toString(array)); // [10, 20, 30, 40]

The mapToInt() method converts a stream of Integer objects back to a stream of int primitives, and .toArray() transforms it into an array.

3. Alternative: Manual Conversion Without Stream API

If you're working with older Java versions or prefer avoiding streams:

int[] arr = {1, 2, 3};
List<Integer> list = new ArrayList<>();
for (int i : arr) {
    list.add(i);
}

int[] backToArray = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
    backToArray[i] = list.get(i);
}

4. Why List<int> Is Not Allowed

Java collections work only with objects, and int is a primitive. That's why we use the wrapper class Integer. Streams help us with boxing (boxed()) and unboxing (mapToInt()).

5. Conclusion

Conversion Method
int[] → List<Integer> Arrays.stream(...).boxed().collect(...)
List<Integer> → int[] list.stream().mapToInt(...).toArray()

Use the Stream API if you want concise and readable code. If you need more control — classic loops are still a great alternative.

Курс 'Java для начинающих' на Udemy Курс 'Java для начинающих' на Udemy
Read also:
Comments