Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting a hashmap in R using rJava

Tags:

java

r

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?

like image 920
gappy Avatar asked Feb 12 '10 01:02

gappy


People also ask

Can we use class as key in HashMap?

We can conclude that to use a custom class for a key, it is necessary that hashCode() and equals() are implemented correctly. To put it simply, we have to ensure that the hashCode() method returns: the same value for the object as long as the state doesn't change (Internal Consistency)

What is rJava?

rJava is a simple R-to-Java interface. It is comparable to the . C/. Call C interface. rJava provides a low-level bridge between R and Java (via JNI).

Can we get key from value in HashMap?

If your hashmap contain unique key to unique value mapping, you can maintain one more hashmap that contain mapping from Value to Key. In that case you can use second hashmap to get key.


2 Answers

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.

like image 104
Mark Avatar answered Sep 27 '22 23:09

Mark


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 )
like image 40
Shane Avatar answered Sep 27 '22 23:09

Shane