Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change items in a list of string in java8

Tags:

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); }  } 
like image 714
oshai Avatar asked Mar 31 '14 09:03

oshai


People also ask

How do I replace a list of items in a string in Java 8?

You can use replaceAll . Replaces each element of this list with the result of applying the operator to that element.

How do I change the value of a list in Java 8?

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.

How do you modify a list element in Java?

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.

How do you update an element in an ArrayList in Java?

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.


1 Answers

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] 
like image 86
Alexis C. Avatar answered Nov 09 '22 11:11

Alexis C.