将 Clojure 数据结构转换为 Java 集合 [英] Converting Clojure data structures to Java collections
问题描述
什么是Clojure惯用的将数据结构转换为Java集合的方式,具体来说:
What is the Clojure-idiomatic way to convert a data structure to a Java collection, specifically:
[]
到java.util.ArrayList
{}
到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?
用例:为了让 Clojure 轻松融入我的组织,我正在考虑为 Clojure 中的全 Java 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 来模拟数据库连接(有没有更好的方法?)并且我的模拟方法需要返回 java.util.List<java.util.Map<String, Object>>代码> 项目(代表数据库行集)给调用者.我会传入一个
[{ "first_name" "Joe" "last_name" "Smith" "date_of_birth" (date "1960-06-13") ... } ...]
结构到我的模拟并将其转换为所需的 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 映射类实现了 java.util.Map
接口,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屋!