Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: HashMap initialization with lambda expressions

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:

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:

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.

like image 657
user35443 Avatar asked Jun 28 '13 14:06

user35443


People also ask

How to initialize the HashMap in Java?

The Static Initializer for a Static HashMap We can also initialize the map using the double-brace syntax: Map<String, String> doubleBraceMap = new HashMap<String, String>() {{ put("key1", "value1"); put("key2", "value2"); }};

How do you iterate through a list in lambda expression?

In Java 8, forEach statement can be used along with lambda expression that reduces the looping through a Map to a single statement and also iterates over the elements of a list. The forEach() method defined in an Iterable interface and accepts lambda expression as a parameter.


2 Answers

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());
  }

}
like image 196
MohamedSanaulla Avatar answered Sep 28 '22 01:09

MohamedSanaulla


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));
like image 24
Nitin Mahesh Avatar answered Sep 28 '22 01:09

Nitin Mahesh