[英]Replace String With hashmap value using java 8 stream
我有String
和HashMap
如下面的代碼:
Map<String, String> map = new HashMap<>();
map.put("ABC", "123");
String test = "helloABC";
map.forEach((key, value) -> {
test = test.replaceAll(key, value);
});
我嘗試用HashMap
值替換字符串,但這不起作用,因為test
是最終的,不能在forEach
的主體中重新分配。
那么有沒有使用Java 8 Stream API用HashMap
替換String
解決方案?
因為這不能只forEach()
( message
必須是有效的最終),解決方法可能是創建一個最終容器(例如List
),它存儲一個重寫的String
:
final List<String> msg = Arrays.asList("helloABC");
map.forEach((key, value) -> msg.set(0, msg.get(0).replace(key, value)));
String test = msg.get(0);
請注意,我將replaceAll()
更改為replace()
因為前者使用正則表達式,但是根據您的代碼進行判斷似乎需要用字符串本身替換(不要擔心,盡管名稱混亂,它也會替換所有出現的事件)。
如果您想要精確的Stream API,可以使用reduce()
操作:
String test = map.entrySet()
.stream()
.reduce("helloABC",
(s, e) -> s.replace(e.getKey(), e.getValue()),
(s1, s2) -> null);
但是要考慮到,這種減少只能在串行(非並行)流中正常工作,其中從不調用組合器函數(因此可以是任何)。
這種問題不適合Streams API。 Streams的當前版本主要針對可以並行的任務。 也許將來會添加對此類操作的支持(請參閱https://bugs.openjdk.java.net/browse/JDK-8133680 )。
您可能會覺得有趣的一種基於流的方法是減少函數而不是字符串:
Function<String, String> combined = map.entrySet().stream()
.reduce(
Function.identity(),
(f, e) -> s -> f.apply(s).replaceAll(e.getKey(), e.getValue()),
Function::andThen
);
String result = combined.apply(test);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.