将数据结构转换为 Java 集合的 Clojure 惯用方法是什么,具体来说:
- 将
[]
转换为 java.util.ArrayList
-
{}
到 java.util.HashMap
-
#{}
到 java.util.HashSet
-
()
到java.util.LinkedList
是否有 clojure.contrib 库可以做到这一点?
用例:为了让 Clojure 轻松融入我的组织,我正在考虑在 Clojure 中为全 Java REST 服务器编写一个单元测试套件。我已经用 Scala 编写了套件的一部分,但认为 Clojure 可能更好,因为宏支持会减少很多样板代码(我需要测试数十个类似的 REST 服务调用)。
我正在使用 EasyMock 来模拟数据库连接(有更好的方法吗?),我的模拟方法需要返回 java.util.List> 项(代表数据库行集)给调用者。我会将 [{ "first_name" "Joe" "last_name" "Smith" "date_of_birth" (date "1960-06-13") ... } ...]
结构传递给我的mock 并将其转换为所需的 Java 集合,以便可以以预期的格式返回给调用者。
What is the Clojure-idiomatic way to convert a data structure to a Java collection, specifically:
[]
to a java.util.ArrayList
{}
to a java.util.HashMap
#{}
to a java.util.HashSet
()
to a java.util.LinkedList
Is there a clojure.contrib library to do this?
USE CASE: In order to ease Clojure into my organization, I am considering writing a unit-test suite for an all-Java REST server in Clojure. I have written part of the suite in Scala, but think that Clojure may be better because the macro support will reduce a lot of the boilerplate code (I need to test dozens of similar REST service calls).
I am using EasyMock to mock the database connections (is there a better way?) and my mocked methods need to return java.util.List<java.util.Map<String, Object>>
items (representing database row sets) to callers. I would pass in a [{ "first_name" "Joe" "last_name" "Smith" "date_of_birth" (date "1960-06-13") ... } ...]
structure to my mock and convert it to the required Java collection so that it can be returned to the caller in the expected format.
发布评论
评论(1)
Clojure 向量、集合和列表类实现了 java.util.Collection 接口,并且 ArrayList、HashSet 和 LinkedList 可以采用 java.util.Collection 构造函数参数。因此,您可以简单地执行以下操作:
类似地,Clojure 映射类实现 java.util.Map 接口,并且 HashMap 接受 java.util.Map 构造函数参数。所以:
你也可以做相反的事情,而且更容易:
Clojure vector, set and list classes implement the
java.util.Collection
interface andArrayList
,HashSet
andLinkedList
can take ajava.util.Collection
constructor argument. So you can simply do:Similarly, Clojure map class implements
java.util.Map
interface andHashMap
takes ajava.util.Map
constructor argument. So:You can also do the reverse and it is much easier: