首页 > 解决方案 > 如何替换 ArrayList 的特定部分?

问题描述

所以我在ArrayList这里:

story.add("Select the type of bread you want to use. Many prefer the taste of [Color] bread, while others prefer [Noun1] bread because it is healthy.");
story.add("Choose the flavor of Jam/Jelly. I personally prefer [Food] jam, but you can use whatever you want.");
story.add(" Choose the type of peanut butter - either [Adjective1] or [Adjective2].");
story.add("Take out [Number] slice(s) of bread.");
story.add(" Use a [Noun2] to [Verb1] the jam all over on of the pieces of bread.");
story.add(" Now [Verb2] the peanut butter on the other piece of bread.");
story.add("Put them together, and you have a PB&J [Verb3].");

我正在尝试替换ArrayList. 例如,我想[Color]用实际颜色替换而不替换整个ArrayList. 这可能吗?

谢谢。

标签: javaarraylist

解决方案


使用 a ListIterator,因此您可以在迭代时替换该值:

for (ListIterator<String> iter = story.listIterator(); iter.hasNext(); ) {
    String line = iter.next();
    line = line.replace("[Color]", "BLUE");
    iter.set(line);
}

story.forEach(System.out::println);

输出

Select the type of bread you want to use. Many prefer the taste of BLUE bread, while others prefer [Noun1] bread because it is healthy.
Choose the flavor of Jam/Jelly. I personally prefer [Food] jam, but you can use whatever you want.
 Choose the type of peanut butter - either [Adjective1] or [Adjective2].
Take out [Number] slice(s) of bread.
 Use a [Noun2] to [Verb1] the jam all over on of the pieces of bread.
 Now [Verb2] the peanut butter on the other piece of bread.
Put them together, and you have a PB&J [Verb3].

如果您想在一次迭代中替换许多占位符,请这样做(Java 9+):

Map<String, String> map = new HashMap<>();
map.put("Color", "BLUE");
map.put("Adjective1", "SMOOTH");
map.put("Adjective2", "CHUNKY");
map.put("Number", "THREE");

Pattern p = Pattern.compile("\\[([^\\]]+)\\]");
for (ListIterator<String> iter = story.listIterator(); iter.hasNext(); ) {
    String line = iter.next();
    line = p.matcher(line).replaceAll(mr -> map.getOrDefault(mr.group(1), mr.group(0)));
    iter.set(line);
}

输出

Select the type of bread you want to use. Many prefer the taste of BLUE bread, while others prefer [Noun1] bread because it is healthy.
Choose the flavor of Jam/Jelly. I personally prefer [Food] jam, but you can use whatever you want.
 Choose the type of peanut butter - either SMOOTH or CHUNKY.
Take out THREE slice(s) of bread.
 Use a [Noun2] to [Verb1] the jam all over on of the pieces of bread.
 Now [Verb2] the peanut butter on the other piece of bread.
Put them together, and you have a PB&J [Verb3].

推荐阅读