繁体   English   中英

将HashMap转换为Clojure映射的行为与Java调用不同

[英]Converting a HashMap into Clojure map performs not as excepted from a java call

我对Clojure非常陌生。 我想将List<HashMap<String,String>>传递给Clojure函数,在其中我想将内部HashMaps用作常规Clojure映射,但是我无法使用:key函数从映射中获取值(对于常规的Clojure映射),但我使用了into {}函数,但除生成外,它没有其他功能。 我做错了什么? (注意:这是一个演示测试代码,仅用于查看行为)

Java代码:

package com.experimental.clojure.java;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.experimental.clojure.test.ConvertTest;

public class Test_Cloj_Convert {
    public static void main(String[] args) {
        List<Map<String, String>> columns = new ArrayList<Map<String, String>>();
        Map<String, String> col1 = new HashMap<String, String>();
        col1.put("name", "ID");
        col1.put("type", "int");
        col1.put("pos", "0");
        Map<String, String> col2 = new HashMap<String, String>();
        col2.put("name", "Name");
        col2.put("type", "string");
        col2.put("pos", "2");
        Map<String, String> col3 = new HashMap<String, String>();
        col3.put("name", "Description");
        col3.put("type", "enum");
        col3.put("pos", "1");
        columns.add(col1);
        columns.add(col2);
        columns.add(col3);

        ConvertTest scripter = new ConvertTest();
        System.out.println(scripter.conv(columns));
    }
}

Clojure代码

(ns com.experimental.clojure.test.ConvertTest
  (:gen-class
   :name com.experimental.clojure.test.ConvertTest
   :methods [
             [conv [java.util.List] String]
  ])
  (:import [java.util List] [java.util HashMap])  
)

(defn conv
    [columns]
    (println columns)
    (println (first columns))
    (println (:type (first columns)))
    (println (into {} (first columns)))
    (println (:type (into {} (first columns))))
)

(defn -conv
  [this columns]
  (conv columns)
)

和(令人惊讶的)输出

#<ArrayList [{name=ID, type=int, pos=0}, {name=Name, type=string, pos=2}, {name=Description, type=enum, pos=1}]>
#<HashMap {name=ID, type=int, pos=0}>
nil
{name ID, type int, pos 0}
nil
null

除第三次println外,我返回的字符串是“ int”。 在第四个println中,很明显HashMap没有正确转换为Clojure映射。 您能帮忙成功转换吗? (我知道我可以使用HashMap的get()函数,但是将其用作Clojure映射会更舒适)

我看到两个问题:

  • 您的conv函数返回nil,因为println是最后一条语句,并且返回nil
  • “:type”是Clojure关键字,它不等于字符串键“ type”-因此,查找无法找到所需的值

我现在了解得更多,这是在问一个愚蠢的事情。 抱歉,但我给人的印象是,在Clojure中,以下两个结构是相同的。 {"a" 1, "b" 2, "c" 3}{:a 1, :b 2, :c 3}它们不是,我尝试使用错误的方法从地图中获取数据。 我尝试使用(println ((into {} (first columns)) "pos")) ,它工作正常。 抱歉,您未及早意识到这一点。

但是,我是否可以再问一次。 它们之间的真正区别是什么? 现在,我对此只有一个模糊的想法。

暂无
暂无

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

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