Java lambdas: copying nodes from a list to a new list

I am new to Java lambdas, and I'm not sure what I want is achievable: I have a list of objects that I would like to filter to extract those that match this condition and put them in a separate list ( so that I can perform some operation on them, keeping the original list intact) I came up with this:

List<Suggestion> only_translations = original_list.stream(). filter(t -> t.isTranslation). collect(Collectors.toCollection(() -> new ArrayList<Suggestion>())); 

But even if I get a new list object, the nodes seem to be linked to the source ones (by reference, not to the new objects copied from the original list), so changing objects in the new list also changes the objects in the original.

So, I would like to know if this can be achieved (using lambda, I know that I can do it in a โ€œclassicโ€ way, iterate through all the elements), and in this case how. Thanks in advance!

+5
source share
2 answers

Assuming your suggestion to some extent has public Suggestion copy(); method (for example, the implementation of the Copyable<Suggestion> interface), you can do:

 List<Suggestion> only_translations = original_list.stream() .filter(t -> t.isTranslation) .map(t -> t.copy()) // or .map(Suggestion::copy) .collect(Collectors.toList())); 

EDIT: with copy constructor:

 List<Suggestion> only_translations = original_list.stream() .filter(t -> t.isTranslation) .map(t -> new Suggestion(t)) // or .map(Suggestion::new) .collect(Collectors.toList())); 
+5
source

Since you say that you have a copy constructor, just add this before the collect operation to get a list of copied objects:

 .map(Suggestion::new) 
+1
source

Source: https://habr.com/ru/post/1268163/


All Articles