简体   繁体   English

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

[英]how to change items in a list of string in java8

I want to change all items in list . 我想更改list所有项目。
What is the correct way to do it with java8 ? 使用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 . 你可以使用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 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 ,但使用流也可以轻松应用过滤器或并行。 replaceAll also modifies the list and throws an exception when the list is unmodifiable, whereas collect creates a new list. replaceAll还修改列表并在列表不可修改时抛出异常,而collect创建新列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM