diff --git a/py/server/deephaven/jcompat.py b/py/server/deephaven/jcompat.py index 98e6a04565e..7569839f558 100644 --- a/py/server/deephaven/jcompat.py +++ b/py/server/deephaven/jcompat.py @@ -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") diff --git a/py/server/tests/test_jcompat.py b/py/server/tests/test_jcompat.py index 40241b73da2..d9d8c5db897 100644 --- a/py/server/tests/test_jcompat.py +++ b/py/server/tests/test_jcompat.py @@ -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: @@ -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) @@ -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()