Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #254 Replace value in list

Replace all exact occurrences of "foo" with "bar" in the string list x

import java.util.ListIterator;
ListIterator<String> i = x.listIterator();
while (i.hasNext())
    if (i.next().equals("foo")) i.set("bar");
x.replaceAll(e -> e.equals("foo") ? "bar" : e);
import java.util.stream.Collectors;
x = x.stream()
     .map(s -> s.equals("foo") ? "bar" : s)
     .toList();
(replace {"foo" "bar"} x)

New implementation...