chrootzius chrootzius - 3 months ago 9
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 = entries.stream().filter(e -> Integer.toString(e.getId()).equals(args[1]))
.map(e -> e).findAny().get();

entries.stream().filter(e -> Integer.toString(e.getId()).equals(args[1]))
.forEach(entry -> {
doneEntries.add(new Entry(entry.getTitle(),
entry.getDescription(),
"done",
entry.getTags(),
doneId));
doneId+=1;
});
entries.remove(id);


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

Try with this:

entries = entries.stream().filter(e -> {
        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;
    }).collect(Collectors.toList());