Skip to content

Instantly share code, notes, and snippets.

@rmg007
Created October 12, 2022 14:57
Show Gist options
  • Select an option

  • Save rmg007/2a922de484095f73385421ccc1e6d6bb to your computer and use it in GitHub Desktop.

Select an option

Save rmg007/2a922de484095f73385421ccc1e6d6bb to your computer and use it in GitHub Desktop.
Remove Elements From List
import java.util.ArrayList;
import java.util.List;
public class RemoveElementsFromList {
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("java","is", "is", "awesome"));
// remove element at index 2
list.remove(2);
//output: [java, is, awesome]
System.out.println(list);
list = new ArrayList<>(List.of("java","is", "is", "awesome", "is"));
// remove the first "is"
list.remove("is");
// output: [java, is, awesome, is]
System.out.println(list);
List<String> auxiliaries = new ArrayList<>(List.of("am", "is", "are"));
list = new ArrayList<>(List.of("java is","is", "are", "awesome", "is"));
// remove all elements that exist in auxiliaries list
list.removeAll(auxiliaries);
// output: [java is, awesome]
System.out.println(list);
List<Integer> integerList = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9));
// remove all even numbers
integerList.removeIf(e-> e % 2 == 0);
// output: [1, 3, 5, 7, 9]
System.out.println(integerList);
List<Integer> first = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
List<Integer> second = new ArrayList<>(List.of(1, 2, 3));
// remove all element from first list and retain only second list element
first.retainAll(second);
System.out.println(first); // [1, 2, 3]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment