Java8 stream style to extract the inside of a map through a list of fields?

For example, given a map as shown below:

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

and a list of fields ["k1","k2","k3"], I need to get a 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 convert the code above to java 8 stream style?

+4
source share
2 answers

I do not think there is any benefit in converting this into a functional style; The loop perfectly and accurately expresses what you are doing.

But for completeness, you can do it like this:

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

, , , map. , .

map reduce, (<Function>):

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

, , , for.

+8

?

fields.stream().reduce(map1, (m, key) -> (Map) m.get(key), (a, b) -> a);
0

Source: https://habr.com/ru/post/1669958/


All Articles