使用java 8流替换String与hashmap值 [英] Replace String With hashmap value using java 8 stream

查看:553
本文介绍了使用java 8流替换String与hashmap值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字符串 HashMap 类似以下代码:

 地图< String,String> map = new HashMap<>(); 
map.put(ABC,123);
String test =helloABC; $(b)b map.forEach((key,value) - > {
test = test.replaceAll(key,value);
});

我尝试用 HashMap 值,但是这不起作用,因为 test 是final,不能在 forEach 主体中重新分配。

那么有什么解决方案可以用 HashMap String >使用Java 8 Stream API?

解决方案

因为只能使用 forEach() code>( message 必须有效),解决方法可以是创建一个最终容器(例如 List ),它存储了重写的单个 String

  final列表与LT;字符串> msg = Arrays.asList(helloABC); $(key,value) - > msg.set(0,msg.get(0).replace(key,value))); 
map.forEach
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);

但是请注意,这种降低只适用于串行(不是并行)流,其中组合器功能从不被调用(因此可能是任何)。


I have String and HashMap like below codes:

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

and I try to replace the string with the HashMap values, but this doesn't work because test is final and cannot be reassigned in the body of forEach.

So are there any solutions to replace String with HashMap using Java 8 Stream API?

解决方案

As this cannot be made using only forEach() (message must be effectively final), workaround could be to create a final container (e. g. List) which stores a single String that is re-written:

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);

Note that I changed replaceAll() to replace() because former works with regex, but judging by your code seems you need replacement by string itself (don't worry, despite of confusing name it also replaces all occurrences).

If you want exactly Stream API, you may use reduce() operation:

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

But take into account, that such reduction will work properly only in serial (not parallel) stream, where combiner function is never called (thus may be any).

这篇关于使用java 8流替换String与hashmap值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆