Looping through java hashmap from ruby through rjb


#1

Greetings.

I am trying to list all keys in a java.util.HashMap field.

The Java code to do this looks like:

Collection c = hMap.values();

//obtain an Iterator for Collection

Iterator itr = c.iterator();

//iterate through HashMap values iterator

while(itr.hasNext())
System.out.println(itr.next());

So, I took a stab at the ruby version:

I have a java hashmap called fields that was created using iText

thusly

reader = pdfreader.new( “pdf_file.pdf” )
@form = reader.getAcroFields()
fields = @form.getFields() # this is a hashmap of all fields on form
fields._classname # entere in irc displays: java.util.HashMap

So, following the java code above

c = fields.values()
itr = c.iterator()
while itr.hasNext()
p itr.next()
end

Instead of getting the field names, I get
#<#Class:0x2d47d74:0x2c15208>
#<#Class:0x2d47d74:0x2c151a4>
#<#Class:0x2d47d74:0x2c150b4>

(there are three keys in the hash)

Any ideas?

Thanks,
Dan


#2

On May 25, 9:28 pm, Dan S. removed_email_address@domain.invalid
wrote:

Well p (or puts etc) end up calling to_s on objects, and you’re
obviously getting Object’s default to_s. Does rjb have some method to
convert java strings into ruby strings ?

Fred


#3

Frederick C. wrote:

On May 25, 9:28�pm, Dan S. removed_email_address@domain.invalid
wrote:

Well p (or puts etc) end up calling to_s on objects, and you’re
obviously getting Object’s default to_s. Does rjb have some method to
convert java strings into ruby strings ?

Fred

Fred,

Good question.

I did some research and found enough to try using itr.next().to_string
and guess what. It worked!

I had tried ruby’s .to_s and naively thought that rjb was translating it
to the java equivalent because I wasn’t getting an error.

Thanks-a-bunch for the guidance,
Dan