I need to convert mutable list object to immutable list. What is the possible way in java?
public void action() {
List mutableList =
Below solution is for making list as Immutable without using any API.
Immutable Object with ArrayList member variable
public final class Demo {
private final List<String> list = new ArrayList<String>();
public Demo() {
list.add("A");
list.add("B");
}
public List<String> getImmutableList() {
List<String> finalList = new ArrayList<String>();
list.forEach(s -> finalList.add(s));
return finalList;
}
public static void main(String[] args) {
Demo obj = new Demo();
System.out.println(obj.getImmutableList());
obj.getImmutableList().add("C");
System.out.println(obj.getImmutableList());
}
}
So the actual list will not change, always output will be [A,B]