Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a HashMap<String, Double> through rJava

Tags:

I'm trying to initialize a HashMap using rJava with type <String, Double> but do not understand how to accomplish this using the rJava interface. I am basically looking for the equivalent of

HashMap<String, Double> x = new HashMap<String, Double>();

but using rJava instead. I can easily produce a HashMap<String, String> as the following example shows, but naturally cannot populate the values with doubles (which is what I want to achieve).

library(rJava)
.jinit()

# this works but gives me a <String, String> hashmap
x <- .jnew("java/util/HashMap")
.jrcall(x, "put", "a", "1")
x

#> [1] "Java-Object{{a=1}}"

# failing example of what I'd like to do
.jrcall(x, "put", "b", 2)

#> Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl,  : 
#>   java.lang.NoSuchMethodException: No suitable method for the given parameters

I have tried to string together combinations using .jcall() in several variations on the following theme:

.jcall("java/util/HashMap",
       "Ljava/util/HashMap;[Ljava/lang/String;Ljava/lang/Double;",
       "<init>")
#> Error in .jcall("java/util/HashMap", "Ljava/util/HashMap; 
#>   [Ljava/lang/String;Ljava/lang/Double;",  : 
#>   method <init> with signature ()Ljava/util/HashMap; 
#>   [Ljava/lang/String;Ljava/lang/Double; not found

But nothing has so far succeeded.

like image 455
Johan Larsson Avatar asked Apr 09 '18 11:04

Johan Larsson


1 Answers

You can create a Double object with .jnew("java/lang/Double", value):

library(rJava)
.jinit()

x <- .jnew("java/util/HashMap")
y <- .jnew("java/lang/Double", 3.14)
.jrcall(x, "put", "a", y)

x
[1] "Java-Object{{a=3.14}}"
like image 167
Juan Mellado Avatar answered Oct 13 '22 14:10

Juan Mellado