Removing via Stream

Starting with JDK 8, we can create a Stream from a collection (Collection.stream()) and filter its elements via filter(Predicate p). The filter will only retain those elements that satisfy the given Predicate.

Finally, we collect these elements via the proper collector:

List<Melon> filteredMelons = melons.stream()
.filter(t -> t.getWeight() >= 3000)
.collect(Collectors.toList());
Unlike the other two solutions, this one doesn't mutate the original collection, but it may be slower and consume more memory.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset