Home  Java   Update elem ...

Update element in ArrayList in Java

In Java, you can “update” elements in an ArrayList using streams.


1️⃣ Using Stream + Filter (“Where” Clause) + Map

Suppose we have a list of employees and want to increase salary by 10% for employees with salary > 50,000.

import java.util.*;
import java.util.stream.Collectors;

class Employee {
    int id;
    String name;
    double salary;

    Employee(int id, String name, double salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }

    @Override
    public String toString() {
        return name + " : " + salary;
    }
}

public class UpdateStreamExample {
    public static void main(String[] args) {
        List<Employee> empList = new ArrayList<>();
        empList.add(new Employee(1, "Sagar", 50000));
        empList.add(new Employee(2, "Neha", 60000));
        empList.add(new Employee(3, "Amit", 55000));

        // Update using stream
        List<Employee> updatedList = empList.stream()
            .map(emp -> {
                if (emp.salary > 50000) {
                    emp.salary *= 1.1; // increase salary by 10%
                }
                return emp;
            })
            .collect(Collectors.toList());

        updatedList.forEach(System.out::println);
    }
}

Output:

Sagar : 50000.0 Neha : 66000.0 Amit : 60500.0

✅ Notes:

filter() can be used to select only matching elements, like a SQL “WHERE” clause.

map() is used to transform/update the element.

collect(Collectors.toList()) gives you a new list with updated objects.


2️⃣ Using Filter Before Map (Optional)

You can filter first, then map only the matching elements:

empList.stream()
       .filter(emp -> emp.salary > 50000) // WHERE clause
       .forEach(emp -> emp.salary *= 1.1); // directly update matching elements

This modifies the original objects in the list.

Works because Employee is a mutable object.

💡 Rule of Thumb:

Use map() + collect() → functional style, creates new list

Use filter() + forEach() → imperative style, modifies original objects

Published on: Oct 06, 2025, 08:25 AM  
 

Comments

Add your comment