Junior — Middle
How to implement a function call for elements inside a collection that does not allow modifications
sobes.tech AI
Answer from AI
If a collection in Java does not allow modifications (for example, it is an immutable list from Collections.unmodifiableList or List.of), then you cannot modify its elements directly. However, you can call a function for each element without changing the collection itself.
To do this, you can use a loop or Stream API:
Example with a loop:
List<String> list = List.of("a", "b", "c"); // immutable collection
for (String item : list) {
process(item); // call function for each element
}
void process(String s) {
System.out.println(s.toUpperCase());
}
Example with Stream API:
list.forEach(item -> process(item));
Important: if the function changes the state of the elements (for example, if the elements are mutable objects), this is possible, but the collection itself will not change (elements will not be added or removed).