Extracting Specific Fields from a Java List into an Array
Using Java Streams to Extract Fields from List Objects
When working with collections, you often need to extract a specific property from each element and create a new array. Java provides multiple approaches to accomplish this, with streams offering the most concise solution.
Using Stream API with map()
The most elegant approach leverages Java 8's Stream API:
import java.util.List;
import java.util.stream.Collectors;
List<User> userList = getUsers();
String[] names = userList.stream()
.map(User::getName)
.toArray(String[]::new);
This method chains map() to extract the desired field and toArray() to convert the stream back into an array.
Using Traditional Loop
For those preferring explicit iteration:
import java.util.ArrayList;
import java.util.List;
List<Product> products = fetchProducts();
List<Integer> prices = new ArrayList<>();
for (Product p : products) {
prices.add(p.getPrice());
}
Integer[] priceArray = prices.toArray(new Integer[0]);
Using forEach with ArrayList
A slightly different pattern:
List<Order> orders = getOrders();
List<Long> orderIds = new ArrayList<>(orders.size());
orders.forEach(order -> orderIds.add(order.getId()));
Long[] ids = orderIds.toArray(new Long[orderIds.size()]);
Complete Working Example
import java.util.*;
class Employee {
private String department;
private double salary;
public Employee(String department, double salary) {
this.department = department;
this.salary = salary;
}
public String getDepartment() {
return department;
}
public double getSalary() {
return salary;
}
}
public class FieldExtractor {
public static void main(String[] args) {
List<Employee> staff = Arrays.asList(
new Employee("Engineering", 75000),
new Employee("Marketing", 65000),
new Employee("Sales", 70000)
);
// Extract departments using stream
String[] departments = staff.stream()
.map(Employee::getDepartment)
.toArray(String[]::new);
// Extract salaries using loop
double[] salaries = new double[staff.size()];
for (int i = 0; i < staff.size(); i++) {
salaries[i] = staff.get(i).getSalary();
}
System.out.println("Departments: " + Arrays.toString(departments));
System.out.println("Salaries: " + Arrays.toString(salaries));
}
}
Performence Considerations
The toArray(new String[0]) approach is actually efficient in modern JVMs. The older recommendation of pre-sizing the array (new String[list.size()]) doesn't provide significant benefits and can be slightly slower in some cases due to intenral array copying.
For primitive types like int, double, or long, consider using IntStream, DoubleStream, or LongStream respectively to avoid autoboxing overhead:
double[] amounts = transactions.stream()
.mapToDouble(Transaction::getAmount)
.toArray();