Mayank
Mayank

Reputation: 5738

py4j: dict to JAVA map

I'm currently working on accessing HBase using python3. The way I'm doing is using py4j to call JAVA APIs that I'm writing to access HBase.

I've a question related to creating a Put object which takes a qualifier and value.

I want to pass a dictionary to a JAVA class which expects a hashmap. Is it possible through py4j.

I don't want to call Put for every column qualifier iteratively. I want to pass the dict to py4j and it should be received as HashMap on JAVA side.

Could you please some hints/pointers to how can this be done...

Upvotes: 1

Views: 3896

Answers (1)

Barthelemy
Barthelemy

Reputation: 8767

There are two ways to do what you want:

  1. You can create a java.util.HashMap() and use it as a dict on the python side. This is good if you pass the dictionary a lot, but you do not modify it often on the python side. This is also good if the dictionary is modified on the java side and you want to see the modifications on the python side.
  2. Py4J can automatically convert a python dict to a HashMap when calling a Java method. Note that the dictionary will be copied and that any change performed on the Java side won't be reflected on the Python side.

The easiest solution would be #1 I believe:

>>> m = gateway.jvm.java.util.HashMap()
>>> m["a"] = 0
>>> m.put("b",1)
>>> m
{u'a': 0, u'b': 1}
>>> u"b" in m
True
>>> del(m["a"])
>>> m
{u'b': 1}
>>> m["c"] = 2 

Upvotes: 2

Related Questions