Created
October 12, 2022 14:57
-
-
Save rmg007/2a922de484095f73385421ccc1e6d6bb to your computer and use it in GitHub Desktop.
Remove Elements From List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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