|
| 1 | +--- |
| 2 | +id: 6a0d1711-a495-490e-a830-95087e092b69 |
| 3 | +slug: "collection-bulk-operations" |
| 4 | +title: "Collection bulk operations instead of mutation loops" |
| 5 | +category: "collections" |
| 6 | +difficulty: "beginner" |
| 7 | +jdkVersion: "8" |
| 8 | +oldLabel: "Iterator mutation loop" |
| 9 | +modernLabel: "Java 8+" |
| 10 | +oldApproach: "Manual iterator removal" |
| 11 | +modernApproach: "Collection.removeIf()" |
| 12 | +oldCode: |- |
| 13 | + for (Iterator<Order> it = orders.iterator(); it.hasNext();) { |
| 14 | + if (it.next().cancelled()) { |
| 15 | + it.remove(); |
| 16 | + } |
| 17 | + } |
| 18 | +modernCode: |- |
| 19 | + orders.removeIf(Order::cancelled); |
| 20 | +summary: "Use removeIf(), replaceAll(), and List.sort() for direct collection transformations." |
| 21 | +explanation: "Modern collection interfaces expose common mutations directly. Methods such as removeIf(), replaceAll(), and List.sort() replace control-flow-heavy loops with operations that state the intended transformation." |
| 22 | +whyModernWins: |
| 23 | +- icon: "👁" |
| 24 | + title: "Clear intent" |
| 25 | + desc: "The operation describes what changes, not how to iterate." |
| 26 | +- icon: "🐛" |
| 27 | + title: "Safer mutation" |
| 28 | + desc: "Avoids manual iterator-removal rules." |
| 29 | +- icon: "⚡" |
| 30 | + title: "Less code" |
| 31 | + desc: "Common transformations become a single expression." |
| 32 | +support: |
| 33 | + state: "available" |
| 34 | + description: "Available since JDK 8 (March 2014)" |
| 35 | +prev: "collections/stack-to-deque" |
| 36 | +next: null |
| 37 | +related: |
| 38 | +- "collections/reverse-list-iteration" |
| 39 | +- "collections/copying-collections-immutably" |
| 40 | +- "streams/predicate-not" |
| 41 | +tags: |
| 42 | +- collections |
| 43 | +- functional |
| 44 | +docs: |
| 45 | +- title: "Collection.removeIf()" |
| 46 | + href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Collection.html#removeIf(java.util.function.Predicate)" |
| 47 | +- title: "List.replaceAll()" |
| 48 | + href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html#replaceAll(java.util.function.UnaryOperator)" |
| 49 | +- title: "List.sort()" |
| 50 | + href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html#sort(java.util.Comparator)" |
0 commit comments