chrootzius chrootzius - 1 year ago 63
Java Question

Manipulate data from within a stream instead of opening two streams

so this is more a performance or best practice question.
I got a List that holds entries of a custom data structure. This looks like:

public class Entry {
private int id;
private String title;
private String description;

So when I want to delete a entry from my list and append it to another list I do this:

Entry id = -> Integer.toString(e.getId()).equals(args[1]))
.map(e -> e).findAny().get(); -> Integer.toString(e.getId()).equals(args[1]))
.forEach(entry -> {
doneEntries.add(new Entry(entry.getTitle(),

I know streams don't manipulate data they create new data so I cant't delete the entry in the second stream. It would cause a ConcurrentModificationException. In my opinion my result is just a workaround and is not very performant.

How to improve this code section?

Thank's in advance

Answer Source

Try with this:

entries = -> {
        boolean result = true;
        if (!Integer.toString(e.getId()).equals(args[1])) {
            doneEntries.add(new Entry(e.getTitle(), e.getDescription(), "done", e.getTags(), doneEntries.size() + 1));
            result = false;
        return result;