Java에서 목록, ArrayList를 반복하는 동안 요소를 제거하는 방법은 무엇입니까? (5가지 방법)
게시 됨: 2021-11-08
Java에서 반복하는 동안 ArrayList에서 요소를 제거하는 방법은 무엇입니까? list.remove(s)는 반복하는 동안 ArrayList에서 항목을 제거하는 경우 java.util.ConcurrentModificationException을 발생시킵니다.
시작하자.
클래스 생성: CrunchifyRemoveItemFromList.java
우리는 그것을 반복하는 동안 ArrayList에서 요소를 제거하기 위해 아래 5 methods
을 사용할 것입니다.
- 방법-1: collectionRemoveIf 메서드
- 방법-2: collectionRemoveIfObjectEquals 메서드
- 방법-3: collectionteratorRemove 메서드
- 방법-4: listIteratorWayToRemoveElement 메서드
- 방법-5: streamFilterCollectWay 메서드
아래 코드를 복사하여 저장합니다.
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 ) ; } } |
위의 프로그램을 Java Application으로 실행하면 아래와 같은 결과를 볼 수 있습니다. 동시 수정 예외가 표시되지 않습니다.

다음은 java.util.Collection.removeIf() 메소드입니다.

IntelliJ IDEA 콘솔 결과:
우리는 작년에 Eclipse에서 IntelliJ IDEA로 옮겼고 그것을 좋아했습니다. 다음은 콘솔 결과입니다.
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 |
이 Java 프로그램을 실행하는 데 문제가 있으면 알려주십시오.