Remove element from collection

We can remove elements from java collection by following ways:

  • Removing collection elements using Iterator
  • Removing collection elements using Collection.removeIf()
  • Removing collection elements using Stream filter

Removing collection elements using Iterator

package com.w3schools;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
/**
 * Removing collection elements using Iterator
 * @author w3schools
 */
public class RemoveCollectionElements {
  public static void main(String[] args) {
	String removeElement = "SQL";
	List<String> subjects = new ArrayList<>();
 
	subjects.add("Java");
	subjects.add("C");
	subjects.add("C++");
	subjects.add("SQL");
	subjects.add("PHP");
 
	System.out.println("Before remove:");
        System.out.println(subjects);
        Iterator<String> iterator = subjects.iterator();
        while(iterator.hasNext()){
        	if(removeElement.equals(iterator.next())){
        		iterator.remove();
            }
        }
        System.out.println("After remove:");
        System.out.println(subjects);
  }
}

Output

Before remove:
[Java, C, C++, SQL, PHP]
After remove:
[Java, C, C++, PHP]

Removing collection elements using Collection.removeIf()

package com.w3schools;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * Removing collection elements using Collection.removeIf()
 * @author w3schools
 */
public class RemoveCollectionElements {
  public static void main(String[] args) {
	List<String> subjects = new ArrayList<>();
 
	subjects.add("Java");
	subjects.add("C");
	subjects.add("C++");
	subjects.add("SQL");
	subjects.add("PHP");
 
	System.out.println("Before remove:");
        System.out.println(subjects);
        subjects.removeIf(e -> e.startsWith("S"));
        System.out.println("After remove:");
        System.out.println(subjects);
  }
}

Output

Before remove:
[Java, C, C++, SQL, PHP]
After remove:
[Java, C, C++, PHP]

Removing collection elements using Stream filter

package com.w3schools;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
 
/**
 * Removing collection elements using Stream filter
 * @author w3schools
 */
public class RemoveCollectionElements {
  public static void main(String[] args) {
	List<String> subjects = new ArrayList<>();
 
	subjects.add("Java");
	subjects.add("C");
	subjects.add("C++");
	subjects.add("SQL");
	subjects.add("PHP");
 
	System.out.println("Before remove:");
        System.out.println(subjects);
        Collection<String> filteredSubjects = subjects
        		  .stream()
        		  .filter(e -> !e.startsWith("S"))
        		  .collect(Collectors.toList());
        System.out.println("After remove:");
        System.out.println(filteredSubjects);
  }
}

Output

Before remove:
[Java, C, C++, SQL, PHP]
After remove:
[Java, C, C++, PHP]