I want to change all items in list
.
What is the correct way to do it with java8
?
public class TestIt { public static void main(String[] args) { ArrayList<String> l = new ArrayList<>(); l.add("AB"); l.add("A"); l.add("AA"); l.forEach(x -> x = "b" + x); System.out.println(l); } }
You can use replaceAll . Replaces each element of this list with the result of applying the operator to that element.
To update or set an element or object at a given index of Java ArrayList, use ArrayList. set() method. ArrayList. set(index, element) method updates the element of ArrayList at specified index with given element.
You can replace an element of an ArrayList using the set() method of the Collections class. This method accepts two parameters an integer parameter indicating the index of the element to be replaced and an element to replace with.
To replace an existing element, we must find the exact position (index) of the element in arraylist. Once we have the index, we can use set() method to update the replace the old element with new element. Find index of existing element using indexOf() method. Use set(index, object) to update new element.
You can use replaceAll
.
Replaces each element of this list with the result of applying the operator to that element.
ArrayList<String> l = new ArrayList<>(Arrays.asList("AB","A","AA")); l.replaceAll(x -> "b" + x); System.out.println(l);
Output:
[bAB, bA, bAA]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With