Java 8:使用 lambda 表达式初始化 HashMap

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17366615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:48:28  来源:igfitidea点击:

Java 8: HashMap initialization with lambda expressions

javacollectionslambdahashmapjava-8

提问by user35443

I'm trying to declare and define larger hash map at once. This is how I do it:

我试图一次声明和定义更大的哈希映射。这就是我的做法:

public HashMap<Integer, Callable<String>> opcode_only = new HashMap<Integer, Callable<String>>() {{
    put(x, y);
    put(x, y);
}};

But, when I try to use lambda expressions in body of put, I'm hitting on eclipse warrning/error. This is how I use lambda in HashMap:

但是,当我尝试在 的主体中使用 lambda 表达式时put,我遇到了 Eclipse 警告/错误。这就是我在 HashMap 中使用 lambda 的方式:

public HashMap<Integer, Callable<String>> opcode_only = new HashMap<Integer, Callable<String>>() {{
    put(0, () -> { return "nop"; });
    put(1, () -> { return "nothing...."; });
}};

Eclipse underlines whole part of lambda starting with comma before. Error messages:

Eclipse 会在前面以逗号开头的整个 lambda 部分下划线。错误信息:

Syntax error on token ",", Name expected    
Syntax error on tokens, Expression expected instead

Does anybody know what am I doing wrong? Is initialization by lambda expression allowed in HashMap? Please help.

有谁知道我做错了什么?中是否允许通过 lambda 表达式进行初始化HashMap?请帮忙。

回答by MohamedSanaulla

This works fine in the Netbeans Lamba builds downloaded from: http://bertram2.netbeans.org:8080/job/jdk8lambda/lastSuccessfulBuild/artifact/nbbuild/

这在从以下位置下载的 Netbeans Lamba 构建中运行良好:http: //bertram2.netbeans.org:8080/job/jdk8lambda/lastSuccessfulBuild/artifact/ nbbuild/

import java.util.*;
import java.util.concurrent.Callable;

public class StackoverFlowQuery {

  public static void main(String[] args) throws Exception {

    HashMap<Integer, Callable<String>> opcode_only = 
          new HashMap<Integer, Callable<String>>() {
            {
              put(0, () -> {
                return "nop";
              });
              put(1, () -> {
                return "nothing....";
              });
            }
          };
    System.out.println(opcode_only.get(0).call());
  }

}

回答by Nitin Mahesh

You are doing correct, update JDK library to 1.8 version from Java Build Path in Eclipse Project properties.

您做得对,将 JDK 库从 Eclipse 项目属性中的 Java 构建路径更新到 1.8 版本。

I just now tried the below code and it is working fine on my Eclipse:

我刚刚尝试了下面的代码,它在我的 Eclipse 上运行良好:

        HashMap<Integer, Integer> hmLambda = new HashMap<Integer, Integer>() {
        {
            put(0, 1);
            put(1, 1);
        }
    };
    System.out.println(hmLambda.get(0));

    hmLambda.forEach((k, v) -> System.out.println("Key " + k
            + " and Values is: " + v));

回答by leiseliesel

As far as I know Netbeans 7.4 fully supports Java 8. I had Problems with eclipse (atm it's not supporting java8 so it's just able to compile the old Lambda expressions of 7), that's why i switched to Netbeans. If you've installed an earlier Version of Netbeans please make sure to FULLY uninstall it to make sure the newer one isn't able to refer to old Logfiles etc.

据我所知,Netbeans 7.4 完全支持 Java 8。我遇到了 eclipse 问题(atm 它不支持 java8,所以它只能编译 7 的旧 Lambda 表达式),这就是我切换到 Netbeans 的原因。如果您安装了较早版本的 Netbeans,请确保完全卸载它以确保较新的版本无法引用旧的日志文件等。