java8 stream style for retrieving a inner part of map through a field list?

房东的猫 提交于 2019-12-04 09:53:56

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.

How about?

fields.stream().reduce(map1, (m, key) -> (Map) m.get(key), (a, b) -> a);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!