Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Extracting Specific Fields from a Java List into an Array

Tech May 14 1

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

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.