本文介绍了java8流风格通过字段列表检索地图的内部部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,给出如下图:

  {
k1:{
k2:{
k3:{
k4:v
}
}
}
}

和字段清单 [k1,k2,k3] ,我需要检索零件 {k4:v}



是我的java7风格的代码:

  // //忽略地图构建代码。 
Map map1 = new HashMap();
Map map2 = new HashMap();
Map map3 = new HashMap();
Map map4 = new HashMap();
map4.put(k4,v);
map3.put(k3,map4);
map2.put(k2,map3);
map1.put(k1,map2);
Map map = map1;
System.out.println(map); // => {k1 = {k2 = {k3 = {k4 = v}}}}

//要转换为java8样式的代码
List< String> fields = Arrays.asList(k1,k2,k3);
for(String field:fields){
map =(Map)map.get(field);
}
System.out.println(map); // => {k4 = v}

然后如何将上面的代码转换成java 8的流风格?

解决方案

我认为将此转化为功能性风格没有任何好处;循环是好的,并精确地表达你在做什么。



但为了完整性,您可以按照以下方式进行:

  map =(Map)fields.stream()
。< Function> map(key - > m - >((Map)m).get (key))
.reduce(Function.identity(),Function :: andThen).apply(map);

这将每个键转换为一个可以对该键进行地图查找的函数,然后将它们组合到一个应用于你的函数 map 。因为函数不允许修改局部变量,所以推迟到那一点是必要的。

< Function> ): reduce 操作, / p>

  map =(Map)fields.parallelStream()
.reduce(Function.identity(),(f,key ) - > f.andThen(m->((Map)m).get(key)),Function :: andThen)
.apply(map);

也许您现在已经认识到,这是一个简单的 for 循环更适合。


For example, given a map like below:

{
  "k1": {
    "k2": {
      "k3": {
        "k4": "v"
      }
    }
  }
}

and a field list ["k1","k2","k3"], I need to retrieve the part {"k4": "v"}.

Below is my java7-style code:

// Ignore the map building code.
Map map1 = new HashMap();
Map map2 = new HashMap();
Map map3 = new HashMap();
Map map4 = new HashMap();
map4.put("k4", "v");
map3.put("k3", map4);
map2.put("k2", map3);
map1.put("k1", map2);
Map map = map1;
System.out.println(map); //=> {k1={k2={k3={k4=v}}}}

// Code to be transformed to java8 style
List<String> fields = Arrays.asList("k1", "k2", "k3");
for(String field: fields) {
    map = (Map) map.get(field);
}
System.out.println(map); //=> {k4=v}

Then how to transform above code to java 8 stream style?

解决方案

I don’t think that there is any benefit in converting this into a functional style; the loop is fine and precisely expresses what you are doing.

But for completeness, you can do it the following way:

map = (Map)fields.stream()
    .<Function>map(key -> m -> ((Map)m).get(key))
    .reduce(Function.identity(), Function::andThen).apply(map);

This converts each key to a function capable of doing a map lookup of that key, then composes them to a single function that is applied to you map. Postponing the operation to that point is necessary as functions are not allowed to modify local variables.

It’s also possible to fuse the map operation with the reduce operation, which allows to omit the explicit type (<Function>):

map = (Map)fields.parallelStream()
 .reduce(Function.identity(), (f, key)->f.andThen(m->((Map)m).get(key)), Function::andThen)
 .apply(map);

Maybe you recognize now, that this is a task for which a simple for loop is better suited.

这篇关于java8流风格通过字段列表检索地图的内部部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 06:27