7

How do I convert LinkedHashMap to java.util.HashMap in groovy?

When I create something like this in groovy, it automatically creates a LinkedHashMap even when I declare it like HashMap h = .... or def HashMap h = ...

I tried doing:

HashMap h = ["key1":["val1", "val2"], "key2":["val3"]]

and

def HashMap h = ["key1":["val1", "val2"], "key2":["val3"]]

h.getClass().getName() still comes back with LinkedHashMap.

tangens
  • 39,095
  • 19
  • 120
  • 139
user140736
  • 1,913
  • 9
  • 32
  • 53

4 Answers4

8

LinkedHashMap is a subclass of HashMap so you can use it as a HashMap.


Resources :

Colin Hebert
  • 91,525
  • 15
  • 160
  • 151
4

Simple answer -- maps have something that looks a lot like a copy constructor:

Map m = ['foo' : 'bar', 'baz' : 'quux'];
HashMap h = new HashMap(m);

So, if you're wedded to the literal notation but you absolutely have to have a different implementation, this will do the job.

But the real question is, why do you care what the underlying implementation is? You shouldn't even care that it's a HashMap. The fact that it implements the Map interface should be sufficient for almost any purpose.

conleym
  • 41
  • 2
  • 1
    I came across the same issue, whereby I am trying to compare a Map in an assertEquals via `assertEquals("Checking Data Input Variable 5/9 - Define attr", ["male": 0, "female": 1], var5.define)` and the assertion fails because the actual type is `HashMap` whereas the expected type is `LinkedHashMap`. Maybe I'll write my own `assertMapEquals()` function that uses your suggestion... – Matthew Wise Mar 30 '15 at 12:30
2

He probably got caught with the dreaded Groovy-Map-Gotcha, and was stumbling around in the wilderness of possibilities as I did for the entire afternoon.

Here's the deal:

When using variable string keys, you cannot access a map in property notation format (e.g. map.a.b.c), something unexpected in Groovy where everything is generally concise and wonderful ;--)

The workaround is to wrap variable keys in parens instead of quotes.

def(a,b,c) = ['foo','bar','baz']  
Map m = [(a):[(b):[(c):1]]]  
println m."$a"."$b"."$c" // 1  
println m.foo.bar.baz // also 1

Creating the map like so will bring great enjoyment to sadists worldwide:

Map m = ["$a":["$b":["$c":1]]]

Hope this saves another Groovy-ist from temporary insanity...

ig0774
  • 39,669
  • 3
  • 55
  • 57
virtualeyes
  • 11,147
  • 6
  • 56
  • 91
1
 HashMap h = new HashMap() 
 h.getClass().getName();

works. Using the [:] notation seems to tie it to LinkedHashMap.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236