java - 如何替换 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
. 这可能吗?
谢谢。
解决方案
使用 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].
推荐阅读
- javascript - Firebase 电子邮件链接身份验证
- php - 在 Woocommerce 中按品牌和标题对产品进行排序
- r - tryCatch 未捕获错误并跳过错误参数
- machine-learning - 用外行的话来说,LossFunction 和 OptimizationAlgorithm 有什么区别?
- android - 使用 Dagger 2 提供应用程序上下文
- python - 如何使用复选按钮激活和停用功能?
- java - 无法将 Lombok 与 Java 11 一起使用
- java - 在 Groovy 中将列表转换为枚举列表
- java - 如何为以下代码解析 Mongo JDBC 驱动程序?
- excel - 数据透视表过滤月份选择当前月份之前的所有内容