24

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);
}

}
1
  • 1
    Remember that everything valid in Java 7 is also valid in Java 8. Thus there are multiple correct ways.
    – user253751
    Mar 31, 2014 at 9:26

2 Answers 2

49

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]
1
  • Thank you @Alexis C. for the answer.
    – Bhala T R
    Jan 20, 2022 at 10:00
17

If you want to use streams, you can do something like that:

List<String> l = new ArrayList<>(Arrays.asList("AB","A","AA"));
l = l.stream().map(x -> "b" + x).collect(Collectors.toList());
System.out.println(l);

Output:

[bAB, bA, bAA]

Of course it is better to use replaceAll if you want to change all elements of a list but using streams enables you to also apply filters or to parallel easily. replaceAll also modifies the list and throws an exception when the list is unmodifiable, whereas collectcreates a new list.

3
  • Could you also explain, why it is better to use Streams? Or explain, what the difference is?
    – bobbel
    Mar 31, 2014 at 12:39
  • I added a comment. The idea was to show another way how it can be implemented using new Java 8 functionality. As immibis said commenting the question there are multiple correct ways how to achieve what was asked.
    – Roland
    Mar 31, 2014 at 13:09
  • Great! Thank you for the further explanation! That's what I wanted to achieve :)
    – bobbel
    Mar 31, 2014 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.