Practical Examples and Use Cases
Example 1: Sorting a Primitive Array
Suppose you have an int
array and you want to sort it. You can convert it to an ArrayList<Integer>
, sort the list, and then convert it back to an array.
int[] intArray = {5, 2, 8, 1, 9};
ArrayList<Integer> intList = Arrays.stream(intArray)
.boxed()
.collect(Collectors.toList());
Collections.sort(intList);
int[] sortedIntArray = intList.stream()
.mapToInt(Integer::intValue)
.toArray();
System.out.println(Arrays.toString(sortedIntArray)); // Output: [1, 2, 5, 8, 9]
Example 2: Filtering a Primitive Array
Let's say you have a double
array and you want to filter out values greater than a certain threshold. You can convert the array to an ArrayList<Double>
, apply the filter, and then convert it back to an array.
double[] doubleArray = {3.14, 2.71, 1.41, 4.2, 2.5};
ArrayList<Double> doubleList = Arrays.stream(doubleArray)
.boxed()
.collect(Collectors.toList());
doubleList.removeIf(value -> value > 3.0);
double[] filteredDoubleArray = doubleList.stream()
.mapToDouble(Double::doubleValue)
.toArray();
System.out.println(Arrays.toString(filteredDoubleArray)); // Output: [2.71, 1.41, 2.5]
Example 3: Integrating with Collections
You can use the converted ArrayList
of wrappers with various collection-related operations, such as searching, filtering, and transforming.
// Creating an ArrayList of Integers
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
// Filtering the ArrayList
ArrayList<Integer> evenNumbers = new ArrayList<>(numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList()));
// Transforming the ArrayList
ArrayList<String> stringNumbers = new ArrayList<>(numbers.stream()
.map(Object::toString)
.collect(Collectors.toList()));
These examples demonstrate how converting primitive arrays to ArrayList
of wrappers can simplify common array manipulation tasks and enable the use of powerful collection-related operations in Java.