问题
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:
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]
回答2:
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.
来源:https://stackoverflow.com/questions/22757764/how-to-change-items-in-a-list-of-string-in-java8