将Clojure数据结构转换为Java集合 [英] Converting Clojure data structures to Java collections
问题描述
将数据结构转换为Java集合的Clojure-Idiomatic方法是什么?具体来说:
What is the Clojure-idiomatic way to convert a data structure to a Java collection, specifically:
-
[] 到
java.util.ArrayList
-
{} code>到
java.util.HashMap
-
#{}
到java.util.HashSet
-
()
java.util.LinkedList
[]
to ajava.util.ArrayList
{}
to ajava.util.HashMap
#{}
to ajava.util.HashSet
()
to ajava.util.LinkedList
是否有clojure.contrib库这个?
Is there a clojure.contrib library to do this?
USE CASE :为了方便Clojure加入我的组织,我考虑编写一个单元测试套件Clojure中的REST服务器。我已经在Scala中编写了套件的一部分,但认为Clojure可能更好,因为宏支持会减少很多样板代码(我需要测试几十个类似的REST服务调用)。
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).
我使用EasyMock模拟数据库连接(有更好的方法吗?),我的mocked方法需要返回 java.util.List< java.util.Map& ,Object>>
项(表示数据库行集)。我会传入 [{first_nameJoelast_nameSmithdate_of_birth(date1960-06-13)...} ...]
结构到我的mock,并将其转换为所需的Java集合,以便它可以以预期的格式返回给调用者。
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.
推荐答案
Clojure向量,集合和列表类实现 java.util.Collection
接口和 ArrayList
, HashSet
和 LinkedList
可以使用 java.util.Collection
构造函数参数。所以你可以简单做:
Clojure vector, set and list classes implement the java.util.Collection
interface and ArrayList
, HashSet
and LinkedList
can take a java.util.Collection
constructor argument. So you can simply do:
user=> (java.util.ArrayList. [1 2 3])
#<ArrayList [1, 2, 3]>
user=> (.get (java.util.ArrayList. [1 2 3]) 0)
1
同样,Clojure map类实现 java.util.Map
interface和 HashMap
接受 java.util.Map
构造函数参数。所以:
Similarly, Clojure map class implements java.util.Map
interface and HashMap
takes a java.util.Map
constructor argument. So:
user=> (java.util.HashMap. {"a" 1 "b" 2})
#<HashMap {b=2, a=1}>
user=> (.get (java.util.HashMap. {"a" 1 "b" 2}) "a")
1
您也可以执行相反的操作,它更容易:
You can also do the reverse and it is much easier:
ser=> (into [] (java.util.ArrayList. [1 2 3]))
[1 2 3]
user=> (into #{} (java.util.HashSet. #{1 2 3}))
#{1 2 3}
user=> (into '() (java.util.LinkedList. '(1 2 3)))
(3 2 1)
user=> (into {} (java.util.HashMap. {:a 1 :b 2}))
{:b 2, :a 1}
这篇关于将Clojure数据结构转换为Java集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!