使用java 8流将String替换为hashmap值

Chh*_*rin 10 java hashmap java-8 java-stream

StringHashMap像下面的代码:

Map<String, String> map = new HashMap<>();
    map.put("ABC", "123");
    String test = "helloABC";
    map.forEach((key, value) -> {
        test = test.replaceAll(key, value);
    });
Run Code Online (Sandbox Code Playgroud)

我尝试用HashMap值替换字符串,但这不起作用,因为test是最终的,不能在正文中重新分配forEach.

那么,有没有任何解决方案,以取代StringHashMap使用Java 8个流API?

Ale*_*you 5

由于不能仅使用它forEach()message必须有效地使用final),因此解决方法是创建一个final容器(例如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);
Run Code Online (Sandbox Code Playgroud)

请注意,我更改replaceAll()replace()因为前者可与regex一起使用,但从您的代码来看,您似乎需要用字符串本身替换(不用担心,尽管名称混乱,它也替换了所有出现的内容)。

如果您确实需要Stream API,则可以使用以下reduce()操作:

String test = map.entrySet()
                 .stream()
                 .reduce("helloABC", 
                         (s, e) -> s.replace(e.getKey(), e.getValue()), 
                         (s1, s2) -> null);
Run Code Online (Sandbox Code Playgroud)

但是要考虑到,这样的减少只能在串行流(而不是并行流)中正常使用,在这种情况下,永远不会调用合并器功能(因此可能是任意的)。