简体   繁体   中英

how to change items in a list of string in java8

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

}

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]

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 collect creates a new list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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