Skip to content

Instantly share code, notes, and snippets.

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

  • Save rmg007/1c815df11d0fe75e13659aaa56f06d02 to your computer and use it in GitHub Desktop.

Select an option

Save rmg007/1c815df11d0fe75e13659aaa56f06d02 to your computer and use it in GitHub Desktop.
Update elements in a list
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