how to change items in a list of string in java8

空扰寡人 提交于 2020-06-27 06:42:35

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!