Getting a hash map in R using rJava

I have a simple hashmap with numerical values ​​and would like to get its contents, ideally in the list (but this can be worked out).

Can this be done?

+3
source share
2 answers

Try the following:

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)
}

Please note that using .jrcall is less efficient than .jcall. But for the life of me I cannot get a signature by using .jcall. I wonder if this is due to the lack of generics.

+4
source

I never did this myself, but there is an example in the rJava documentation of creating and working with HashMap with with:

HashMap <- J("java.util.HashMap")
with( HashMap, new( SimpleEntry, "key", "value" ) )
with( HashMap, SimpleEntry )
+1
source

Source: https://habr.com/ru/post/1732457/


All Articles