BAEL-3142 Removing an element from an ArrayList
This commit is contained in:
parent
4e926d3f06
commit
db772047f4
|
@ -0,0 +1,40 @@
|
|||
package com.baeldung.java.list;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
public class RemoveFromList {
|
||||
|
||||
public static void main(String[] args) {
|
||||
List<String> sports = new ArrayList<>();
|
||||
sports.add("Football");
|
||||
sports.add("Basketball");
|
||||
sports.add("Baseball");
|
||||
sports.add("Boxing");
|
||||
sports.add("Cycling");
|
||||
|
||||
System.out.println("List before removing: " + sports);
|
||||
|
||||
// Remove with index
|
||||
sports.remove(1);
|
||||
|
||||
// Remove with an element
|
||||
sports.remove("Baseball");
|
||||
|
||||
// Iterator remove method
|
||||
Iterator<String> iterator = sports.iterator();
|
||||
while(iterator.hasNext()){
|
||||
if(iterator.next().equals("Boxing")){
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
|
||||
// ArrayList removeIf method (Java 8)
|
||||
for(int i = 0; i < sports.size(); i++){
|
||||
sports.removeIf(p -> p.equals("Cycling"));
|
||||
}
|
||||
|
||||
System.out.println("List after removing: " + sports);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue