Friday, January 16, 2026

Mutable and Immutable Lists - The Many Ways

---------------------------------------------------------------

Suppose there is an Employee Array like below statement

Employee[] employee = empoyeeService.getEmployee(employeeId);

and 

(1)if we want an Immutable List then we can give the below 

List<Rating> ratings2 = Arrays.stream(ratings1).toList();

(2)But if we want an Mutable List then we have to give like the below 2 Options

// Option 1: Using Collectors.toList() (returns ArrayList which is mutable)

List<Employee> employee = Arrays.stream(employee).collect(Collectors.toList());

// Option 2: Using Collectors.toCollection() (explicitly specify the List implementation)

List<Employee> employee = Arrays.stream(employee)

                            .collect(Collectors.toCollection(ArrayList::new));

No comments:

Post a Comment