Skip to content

Commit

Permalink
feat: Add j_collection_to_list() in jcompat.py (#6565)
Browse files Browse the repository at this point in the history
Fixes #6515 

This new function, unlike the existing j_list_to_list(),
j_map_to_dict(), covers Set and can be used when the concrete collection
type is unknown.
  • Loading branch information
jmao-denver authored Jan 15, 2025
1 parent a8eea36 commit 6682564
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
13 changes: 13 additions & 0 deletions py/server/deephaven/jcompat.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,19 @@ def j_list_to_list(jlist) -> List[Any]:
return [wrap_j_object(jlist.get(i)) for i in range(jlist.size())]


def j_collection_to_list(jcollection) -> List[Any]:
"""Converts a java Collection to a python list."""
if not jcollection:
return []

res = []
it = jcollection.iterator()
while it.hasNext():
res.append(wrap_j_object(it.next()))

return res


T = TypeVar("T")
R = TypeVar("R")

Expand Down
13 changes: 12 additions & 1 deletion py/server/tests/test_jcompat.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@
import unittest

from deephaven import dtypes
from deephaven.jcompat import j_function, j_lambda, AutoCloseable
from deephaven.jcompat import j_function, j_lambda, AutoCloseable, j_array_list, j_collection_to_list, j_hashset
from tests.testbase import BaseTestCase

import jpy

_JSharedContext = jpy.get_type("io.deephaven.engine.table.SharedContext")


class JCompatTestCase(BaseTestCase):
def test_j_function(self):
def int_to_str(v: int) -> str:
Expand All @@ -25,6 +26,7 @@ def int_to_str(v: int) -> str:
def test_j_lambda(self):
def int_to_str(v: int) -> str:
return str(v)

j_func = j_lambda(int_to_str, jpy.get_type('java.util.function.Function'), dtypes.string)

r = j_func.apply(10)
Expand All @@ -36,6 +38,15 @@ def test_auto_closeable(self):
self.assertEqual(auto_closeable.closed, False)
self.assertEqual(auto_closeable.closed, True)

def test_j_collection_to_list(self):
lst = [2, 1, 3]
j_list = j_array_list(lst)
self.assertEqual(lst, j_collection_to_list(j_list))

s = set(lst)
j_set = j_hashset(s)
self.assertEqual(s, set(j_collection_to_list(j_set)))


if __name__ == "__main__":
unittest.main()

0 comments on commit 6682564

Please sign in to comment.