简体   繁体   English

将Clojure数据结构转换为Java集合

[英]Converting Clojure data structures to Java collections

What is the Clojure-idiomatic way to convert a data structure to a Java collection, specifically: 什么是将数据结构转换为Java集合的Clojure-idiomatic方法,具体为:

  • [] to a java.util.ArrayList []java.util.ArrayList
  • {} to a java.util.HashMap {}java.util.HashMap
  • #{} to a java.util.HashSet #{}java.util.HashSet
  • () to a java.util.LinkedList ()java.util.LinkedList

Is there a clojure.contrib library to do this? 是否有clojure.contrib库来执行此操作?

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. 使用案例 :为了使Clojure易于进入我的组织,我正在考虑为Clojure中的全Java REST服务器编写单元测试套件。 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). 我已经在Scala中编写了部分套件,但认为Clojure可能更好,因为宏支持将减少很多样板代码(我需要测试几十个类似的REST服务调用)。

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. 我使用EasyMock来模拟数据库连接(有更好的方法吗?),我的模拟方法需要将java.util.List<java.util.Map<String, Object>>项(代表数据库行集)返回给调用者。 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. 我会将[{ "first_name" "Joe" "last_name" "Smith" "date_of_birth" (date "1960-06-13") ... } ...]结构传递给我的模拟并将其转换为必需的Java集合,以便它可以以预期的格式返回给调用者。

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. Clojure向量,集合和列表类实现了java.util.Collection接口和ArrayListHashSetLinkedList可以采用java.util.Collection构造函数参数。 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

Similarly, Clojure map class implements java.util.Map interface and HashMap takes a java.util.Map constructor argument. 同样,Clojure map类实现java.util.Map接口, HashMap接受java.util.Map构造函数参数。 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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM