Java 8: HashMap initialization with lambda expressions

前端 未结 3 805
面向向阳花
面向向阳花 2021-02-13 06:49

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

public HashMap> opcode_only = new HashMap&l         


        
相关标签:
3条回答
  • 2021-02-13 07:17

    This works fine in the Netbeans Lamba builds downloaded from: 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());
      }
    
    }
    
    0 讨论(0)
  • 2021-02-13 07:19

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

    I just now tried the below code and it is working fine on my 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));
    
    0 讨论(0)
  • 2021-02-13 07:22

    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.

    0 讨论(0)
提交回复
热议问题