In Java Wie entferne ich Elemente beim Iterieren einer Liste, ArrayList? (5 verschiedene Möglichkeiten)
Veröffentlicht: 2021-11-08
In Java Wie entferne ich Elemente aus ArrayList während der Iteration? list.remove(s) löst java.util.ConcurrentModificationException aus, wenn Sie ein Element aus einer ArrayList entfernen, während Sie es durchlaufen.
Lass uns anfangen.
Klasse erstellen: CrunchifyRemoveItemFromList.java
Wir werden die folgenden 5 methods
, um ein Element aus ArrayList zu entfernen, während wir es durchlaufen.
- Methode-1: collectionRemoveIf-Methode
- Methode-2: collectionRemoveIfObjectEquals-Methode
- Methode-3: collectionteratorRemove-Methode
- Methode-4: listIteratorWayToRemoveElement-Methode
- Methode-5: streamFilterCollectWay-Methode
Kopieren Sie den folgenden Code und speichern Sie ihn.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 |
package crunchify . com . java . tutorials ; import java . util . ArrayList ; import java . util . List ; import java . util . ListIterator ; import java . util . Objects ; import java . util . stream . Collectors ; /** * @author Crunchify.com * In Java How to remove Elements while Iterating a List? (5 different ways to remove items) */ public class CrunchifyRemoveItemFromList { public static void main ( String [ ] args ) { collectionRemoveIfMethod ( ) ; collectionRemoveIfObjectEqualsMethod ( ) ; collectionteratorRemoveMethod ( ) ; listIteratorWayToRemoveElement ( ) ; streamFilterCollectWay ( ) ; } // Method-1: collectionRemoveIfMethod to remove elements from ArrayList private static void collectionRemoveIfMethod ( ) { List < String > crunchifyList = new ArrayList < > ( ) ; crunchifyList . add ( "Google.com" ) ; crunchifyList . add ( "Crunchify.com" ) ; crunchifyList . add ( "Facebook.com" ) ; crunchifyList . add ( "Apple.com" ) ; // removeIf(): Removes all of the elements of this collection that satisfy the given predicate. // Errors or runtime exceptions thrown during iteration or by the predicate are relayed to the caller. crunchifyList . removeIf ( "Apple.com" : : equals ) ; // equals(): Compares this string to the specified object. // The result is true if and only if the argument is not null and is a // String object that represents the same sequence of characters as this object. // For finer-grained String comparison, refer to java.text.Collator. System . out . print ( "Method-1 Result: " ) ; crunchifyPrint ( crunchifyList ) ; } // Simple print function private static void crunchifyPrint ( List < String > crunchifyList ) { System . out . println ( crunchifyList ) ; } // Method-2: collectionRemoveIfObjectEqualsMethod to remove elements from ArrayList private static void collectionRemoveIfObjectEqualsMethod ( ) { List < String > crunchifyList = new ArrayList < > ( ) ; crunchifyList . add ( "Google.com" ) ; crunchifyList . add ( "Crunchify.com" ) ; crunchifyList . add ( "Facebook.com" ) ; crunchifyList . add ( "Apple.com" ) ; // removeIf() Params: // filter – a predicate which returns true for elements to be removed // Returns: // true if any elements were removed // Throws: // NullPointerException – if the specified filter is null crunchifyList . removeIf ( crunchify - > Objects . equals ( crunchify , "Crunchify.com" ) | | Objects . equals ( crunchify , "Apple.com" ) ) ; System . out . print ( "Method-2 Result: " ) ; crunchifyPrint ( crunchifyList ) ; } // Method-3: collectionteratorRemoveMethod to remove elements from ArrayList private static void collectionteratorRemoveMethod ( ) { List < String > crunchifyList = new ArrayList < > ( ) ; crunchifyList . add ( "Google.com" ) ; crunchifyList . add ( "Crunchify.com" ) ; crunchifyList . add ( "Facebook.com" ) ; crunchifyList . add ( "Apple.com" ) ; // listIterator(): Returns a list iterator over the elements in this list (in proper sequence). ListIterator < String > crunchifyIterator = crunchifyList . listIterator ( ) ; // hasNext(): Returns true if this list iterator has more elements when traversing the list in the forward direction. // (In other words, returns true if next would return an element rather than throwing an exception.) while ( crunchifyIterator . hasNext ( ) ) { // equals(): Compares this string to the specified object. // The result is true if and only if the argument is not null and is a // String object that represents the same sequence of characters as this object. //For finer-grained String comparison, refer to java.text.Collator. if ( "Crunchify.com" . equals ( crunchifyIterator . next ( ) ) ) { // next(): returns the next element in the list and advances the cursor position. // This method may be called repeatedly to iterate through the list, or intermixed with calls to previous to go back and forth. // (Note that alternating calls to next and previous will return the same element repeatedly.) crunchifyIterator . remove ( ) ; // remove(): Removes from the list the last element that was returned by next or previous (optional operation). // This call can only be made once per call to next or previous. It can be made only if add has not been called after the last call to next or previous. } } System . out . print ( "Method-3 Result: " ) ; crunchifyPrint ( crunchifyList ) ; } // Method-4: listIteratorWayToRemoveElement to remove elements from ArrayList private static void listIteratorWayToRemoveElement ( ) { List < String > crunchifyList = new ArrayList < > ( ) ; crunchifyList . add ( "Google.com" ) ; crunchifyList . add ( "Crunchify.com" ) ; crunchifyList . add ( "Facebook.com" ) ; crunchifyList . add ( "Apple.com" ) ; List < String > crunchifyNewList = new ArrayList < > ( ) ; for ( String s : crunchifyList ) { if ( ! "Facebook.com" . equals ( s ) ) { crunchifyNewList . add ( s ) ; } } System . out . print ( "Method-4 Result: " ) ; crunchifyPrint ( crunchifyNewList ) ; } // Method-5: streamFilterCollectWay to remove elements from ArrayList private static void streamFilterCollectWay ( ) { List < String > crunchifyList = new ArrayList < > ( ) ; crunchifyList . add ( "Google.com" ) ; crunchifyList . add ( "Crunchify.com" ) ; crunchifyList . add ( "Facebook.com" ) ; crunchifyList . add ( "Apple.com" ) ; // stream(): Returns a sequential Stream with this collection as its source. // This method should be overridden when the spliterator() method cannot return a spliterator // that is IMMUTABLE, CONCURRENT, or late-binding. (See spliterator() for details.) // filer(): Returns a stream consisting of the elements of this stream that match the given predicate. // This is an intermediate operation. List < String > crunchifyNewList = crunchifyList . stream ( ) . filter ( crunchify - > ! "Crunchify.com" . equals ( crunchify ) ) . collect ( Collectors . toList ( ) ) ; // toList(): Returns a Collector that accumulates the input elements into a new List. // There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; // if more control over the returned List is required, use toCollection(Supplier). System . out . print ( "Method-5 Result: " ) ; crunchifyPrint ( crunchifyNewList ) ; } } |
Führen Sie einfach das obige Programm als Java-Anwendung aus und Sie werden das Ergebnis wie unten sehen. Sie werden keine Concurrent Modification Exception sehen.

Hier ist die Methode java.util.Collection.removeIf():

Ergebnis der IntelliJ IDEA-Konsole:
Wir sind letztes Jahr von Eclipse zu IntelliJ IDEA gewechselt und waren begeistert. Hier ist ein Konsolenergebnis.
1 2 3 4 5 6 7 8 9 |
/ Users / app / Library / Java / JavaVirtualMachines / openjdk - 17.0.1 / Contents / Home / bin / java -- enable - preview - javaagent : / Applications / IntelliJ IDEA . app / Contents / lib / idea_rt . jar crunchify . com . java . tutorials . CrunchifyRemoveItemFromList Method - 1 Result : [ Google . com , Crunchify . com , Facebook . com ] Method - 2 Result : [ Google . com , Facebook . com ] Method - 3 Result : [ Google . com , Facebook . com , Apple . com ] Method - 4 Result : [ Google . com , Crunchify . com , Apple . com ] Method - 5 Result : [ Google . com , Facebook . com , Apple . com ] Process finished with exit code 0 |
Lassen Sie mich wissen, wenn Sie beim Ausführen dieses Java-Programms auf Probleme stoßen.