Created
October 12, 2022 14:33
-
-
Save rmg007/1c815df11d0fe75e13659aaa56f06d02 to your computer and use it in GitHub Desktop.
Update elements in a 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 UpdateElementsInList { | |
| public static void main(String[] args) { | |
| List<Integer> intList = new ArrayList<>(List.of(1, 2, 3)); | |
| // all elements will be updated | |
| // output: [2, 4, 6] | |
| intList.replaceAll(e -> e * 2); | |
| System.out.println(intList); | |
| List<String> strList = new ArrayList<>(List.of("java", "is", "awesome")); | |
| /* | |
| // this will update all string to be all caps | |
| you can also use Method reference | |
| strList.replaceAll(String::toUpperCase); | |
| output: [JAVA, IS, AWESOME] | |
| */ | |
| strList.replaceAll(e -> e.toUpperCase()); | |
| System.out.println(strList); | |
| // will update element at index 0 to be 9999 | |
| // output: [9999, 4, 6] | |
| intList.set(0, 9999); | |
| System.out.println(intList); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment