BAEL-3142 Removing an element from an ArrayList

This commit is contained in:
David Calap 2019-09-01 20:30:58 +02:00
parent 4e926d3f06
commit db772047f4
1 changed files with 40 additions and 0 deletions

View File

@ -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);
}
}