Java lambdas: Copy nodes from list to a new list

motagirl2 :

I am quite new to Java lambdas, and I am not sure if what I want is achievable: I have a list of objects, which I'd like to filter to extract those of them that are matching a given condition, and put them in a separated list (so I can perform some operation on them, keeping the original list unmodified) 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 am getting a new list object, the nodes seem to be linked to the original ones (by reference, not new objects copied from the original list), so modifying the objects in the new list is modifying also the objects in the original one.

So, I'd like to know if it's posible to achieve that (using lambdas, I know I can do it the "classical" way iterating all the elements), and in that case, how. Thanks in advance!

Jeremy Grand :

Assuming your Suggestion somewhat possess a public Suggestion copy(); method (like implementing a Copyable<Suggestion> interface), you could 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 the 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()));

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=469233&siteId=1