简体   繁体   中英

Map.of for Java in Scala

How to call static varg overloads of java Map from Scala?

for ex:

 val map: java.util.Map[Char,Int] =
  java.util.Map.of('Z', 5, 'R', 2, 'X', 9, 'A', 4, 'F', 1)

This fails with Error as Scala treats of as member of Map.

    Value of is not a member of object java.util.Map
          java.util.Map.of('Z', 5, 'R', 2, 'X', 9, 'A', 4, 'F', 1)
                        ^Compilation Failed 

Note that Map.of was introduced with Java SE 9 and therefore your code will fail to compile with pre-Java9 JDK.

Another important fact you should keep in mind is that using Map.of , you can store a maximum of 10 entries only, and for each number of entries (zero to 10), there is a separate Map.of defined. So, it's NOT a varg.

eg the following statement is correct

Map<Character, Integer> map = Map.of('A', 1, 'B', 2, 'C', 3, 'D', 4, 'E', 5, 'F', 6, 'G', 7, 'H', 8, 'I', 9,
                'J',  10);

but NOT the following one:

Map<Character, Integer> map = Map.of('A', 1, 'B', 2, 'C', 3, 'D', 4, 'E', 5, 'F', 6, 'G', 7, 'H', 8, 'I', 9,
                'J', 10,'K',11);

If you want to store more than 10 entries using a single statement like this, you can use Map#ofEntries .

Demo:

import static java.util.Map.entry;

import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<Character, Integer> map = Map.ofEntries(entry('A', 1), entry('B', 2), entry('C', 3), entry('D', 4),
                entry('E', 5), entry('F', 6), entry('G', 7), entry('H', 8), entry('I', 9), entry('J', 10),
                entry('K', 11));

        System.out.println(map);
    }
}

Output:

{K=11, J=10, I=9, H=8, G=7, F=6, E=5, D=4, C=3, B=2, A=1}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM