tags:

views:

194

answers:

2

The title says is it all: I have a plain hashmap with numeric values and would like to retrieve its content, ideally in a list (but that can be worked out). Can it be done?

+1  A: 

I have never done this myself, but there is an example in the rJava documentation of creating and working with a HashMap using the with function:

HashMap <- J("java.util.HashMap")
with( HashMap, new( SimpleEntry, "key", "value" ) )
with( HashMap, SimpleEntry )
Shane
thanks Shane. It'd be useful if rJava had a few examples in the opposite direction.
gappy
+1  A: 

Try this:

library(rJava)
.jinit()
# create a hash map
hm<-.jnew("java/util/HashMap")
# using jrcall instead of jcall, since jrcall uses reflection to get types 
.jrcall(hm,"put","one", "1")
.jrcall(hm,"put","two","2")
.jrcall(hm,"put","three", "3")

# convert to R list
keySet<-.jrcall(hm,"keySet")
an_iter<-.jrcall(keySet,"iterator")
aList <- list()
while(.jrcall(an_iter,"hasNext")){
  key <- .jrcall(an_iter,"next");
  aList[[key]] <- .jrcall(hm,"get",key)
}

Note that using .jrcall is less efficient than .jcall. But for the life of me I can not get the method signature right with .jcall. I wonder if it has something to do with the lack of generics.

Mark