Jay Taylor's notes
back to listing indexHow to populate java.util.HashMap on the fly from Scala code? - Stack Overflow
[web search]
There are a bunch of different ways to accomplish this, only some of which have appeared in the answers thus far. Method One: Since
The downsides here are that you have to already have a Scala map (slightly wasteful if you're just going to create a Java one, perhaps), and that you have to specify the types. But it's compact and painless. Method Two: Alternatively, you can create a new code block as the declaration statement, so you don't even need to have
Slightly less compact, but completely general, and as efficient (or inefficient) as you care to make it. Method Three: Also, you can create an anonymous subclass of HashMap as long as it's okay to have a subclass (i.e.
The downside is, of course, that it's a subclass of Method Four: And finally, of course, you can create a method that does what you want and call it instead:
This is barely less compact than the others and gets the types correct without you having to specify them, so it can be an appealing choice if you're doing this more than once. P.S. Just for fun, I've shown a variety of ways of getting some key-value pairs into the map, but they're not specific to a given method (except for #1 which requires a map). Mix and match at your preference.
| ||||
add comment |
All the methods and constructors of
| |||
add comment |
Building on Randall's answer, you can use
| |||
add comment |
You could do the map as an anonymous class, and do the initialization as part of the instance initialization of the object.
This actually works equally well in Java (except for requiring double-braces {{}}), but is much more idiomatic in Scala.
| |||||||||||||||||||||
|
To make something reusable it would be possible to create a new "Map" subtype just for initialization syntax. It could work something like this (I'm ignoring generics because I don't use them regularly and I'd probably get something wrong):
There would be more code involved in the InitMap class but it would be reusable and fairly straight-forward (I really like array initialization syntax for this kind of stuff). Thinking about it, the InitMap class wouldn't be too hard. You'd probably want to figure out which methods were called and just implement those. Chances are it would only call the KeySet and EntrySet methods. Of course at this rate you could simple create a helper method that took the two arrays and returned a HashMap or extend HashMap and add a new constructor... | |||
add comment |