如何在java8中更改字符串列表中的项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22757764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:44:26  来源:igfitidea点击:

how to change items in a list of string in java8

javalistjava-8

提问by oshai

I want to change all items in list.
What is the correct way to do it with java8?

我想更改list.
正确的做法是什么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);
}

}

采纳答案by Alexis C.

You can use replaceAll.

您可以使用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]

回答by Roland

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 replaceAllif you want to change all elements of a list but using streams enables you to also apply filters or to parallel easily. replaceAllalso modifies the list and throws an exception when the list is unmodifiable, whereas collectcreates a new list.

当然,如果您想更改列表的所有元素,最好使用replaceAll,但使用流使您还可以轻松应用过滤器或并行。replaceAll也会修改列表并在列表不可修改时抛出异常,同时collect创建一个新列表。