Home > Back-end >  convert list of strings to list of java type objects in clojure
convert list of strings to list of java type objects in clojure

Time:10-16

I am using mongo java driver along with clojure for mongo connection, to establish connection in java I am using following code snippet

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.ServerAddress;

MongoClientURI uri = new MongoClientURI("mongodb://xxx:***@url:27017/test?readPreference=primary");
List<String> hosts = uri.getHosts();
List<ServerAddress> serverList = new LinkedList<>();

for(String host:hosts) {
    serverList.add(new ServerAddress(host)); //updated
}

I want to get this same functionality in clojure so I tried this

(def uri (MongoClientURI. uri))
(def hosts (.getHosts uri))

Now I have List of hosts which are String, how do I convert them to list of type ServerAddress ?

CodePudding user response:

What's perhaps a little hard to spot in the Java code is that because serverList is a List<ServerAddress>, when you add String objects to that, they are implicitly converted to ServerAddress objects via the latter's constructor.

Something like the following should get you what you want:

(def host (map #(ServerAddress. %) (.getHosts uri)))

Note that you'll have a Clojure sequence at that point -- if you are passing it into Java methods, you may need to type hint it or even pour it into a (mutable) Java List.

  • Related