-1

I am passing a person list to local method. In this method, I am streaming with passed list and creating a new list. My concern is that if I update for the newly created list, it is affecting the passed list. I am sending piece of code. How to maintain mutable for passed list.

private void checkMutable(List<person> personList) {
    List<person> personNewList = personList.stream()
          .map(person->person)
          .collect(Collectors.toList());

    personNewList.stream().forEach(p -> {
        p.setEmail("ccc@gmail.com");
        p.setName("ccc");
    });

    personList.stream().forEach(p -> {
        System.out.println("name : " + p.getName() + "  ---  " + "name : " + p.getEmail());
    });
khelwood
  • 55,782
  • 14
  • 81
  • 108
MJava143
  • 1
  • 5
  • can some one give answer for this. – MJava143 Mar 29 '19 at 09:35
  • Your `map(person->person)` serves no purpose. Your new list contains the same objects as the old list. If you alter them, you're altering the original objects. If you want _copies_ of your `person` objects, you need to have some code for copying that object, not just copying the list. – khelwood Mar 29 '19 at 09:36
  • If you want to deep copy your list, this isnt the best way to do it... – vikingsteve Mar 29 '19 at 09:36
  • person->person.clone() might work in this instance, but it doesnt seem nice design on first glance... – vikingsteve Mar 29 '19 at 09:38
  • do we have any other way to copy this object without using clone method. – MJava143 Mar 29 '19 at 09:41

1 Answers1

0

In your case, when you create a new person list(personNewList), you can return a new instance of Person instance of returning the same person.

I have added below method in Person class

public static Person copyOf(Person person) {
    return new Person(person.getEmail(),person.getName());
}

and used this method in the filter predicate to create a new instance of Person

List<Person> personNewList = personList.stream().map(person -> 
                             Person.copyOf(person)).collect(Collectors.toList());

If you truly want to make the Person class mutable, follow below link

Ashishkumar Singh
  • 3,580
  • 1
  • 23
  • 41