使用Java 8 lambda迭代映射键

时间:2015-10-28 21:21:19

标签: java lambda java-8

我有一个嵌套地图<a onclick="navVideo('@items.FileName','@items.StartSec');">@items.DisplayText</a> function navVideo(fileName, pos) { //Get Player and the source var player = document.getElementById('VideoContainer'); var mp4Vid = document.getElementById('VideoData'); var mp4CurVid = $(mp4Vid).attr('src'); //Reload the player only if the file name changes if (mp4CurVid != fileName) { $(mp4Vid).attr('src', fileName); player.load(); player.play(); if (pos != 0) { setTimeout(function () { player.currentTime = pos; player.play(); }, 1000); } } else { player.pause(); player.currentTime = pos; player.play(); }

我如何使用Java 8 lambdas在地图上导航。这里可能有必要的解决方案:

Map<String, Map<String, Map<String, ...>

2 个答案:

答案 0 :(得分:5)

如评论中所示,我完全不了解这一点。应将json文档转换为适当类型的Java对象,而不是某些高度嵌套的Map<String, Map<String, Map<String, ...>>>

即使没有lambdas,这也需要从ObjectMap<String, Object>的未经检查的强制转换,并且在运行时很容易因ClassCastException而失败。

在此基础上添加lambdas会增加额外的复杂性,因为lambda体中使用的变量必须是最终的,而head在每个阶段都会重新分配。你可以使用长度为1的数组来解决这个问题。

生成的代码很可怕(而且我推荐这个),但它实现了你的要求:

Object[] head = {mainMap};
Stream.of(key.split(".")).forEach(s -> {
    head[0] = ((Map<String, ?>) head[0]).get(s);
});
return head[0]; 

答案 1 :(得分:1)

当您需要提供具有单一方法的任何接口的实例时,Lambda适用,例如Runnable

例如:

new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("Running on thread: " + Thread.currentThread());
    }
}).start();

可以转换为:

new Thread(() -> {
    System.out.println("Running on thread: " + Thread.currentThread());
}).start();

甚至:

new Thread(() -> System.out.println("Running on thread: " + Thread.currentThread())).start();

在你的情况下,我看不到你需要这样的实例。

相关问题