The question about how to change the java code to clojure with same function? 

I want to change this java code to clojure, but how to do that, and how to make clojure code do the same work?

Bellow it the Java class A and B code:

B.java:

package b;

public class B {
 int c;
}

A.java:

package b;

import java.util.*;

public class A {

 public static void findElement(List<B> a)
 {
    a.forEach((z) -> {
        if (z.c == 1) {
            System.out.println(z.c);
        }
    });
 }
 public static void main(String[] args) {
    // TODO Auto-generated method stub
    B x = new B();
    x.c = 1;
    B y = new B();
    y.c = 2;
    List<B> d = new ArrayList<B>();
    d.add(x);
    d.add(y);
    findElement(d);
 }
}

I searched for some information , and I had tried to use defrecord and defprotocol times,but it failed.

Is there any good solution?


How to change this java code to clojure with same function?The Avaliable solution from the Internet to change this java code to clojure with same function.

It looks that you used so many mutations in the code, and the Clojure is a language that highly encourages immutability.

This is a short snippet:

(defrecord B [c])

(defn find-element [bs]
  (filter #(= (:c %) 1) bs))

(let [x (->B 1)
      y (->B 2)
      d [x y]
      r (find-element d)]
  (doseq [i r]
    (println (:c i)))) 

However, instead of printing the elements inside find-element, we usually return the found results and store them in r. Then we use doseq to go over every item to print it.

It’s not a very good way to think in Clojure, I am not sure what you are trying to achieve, but this is a little bloated and OO-full.

Here, I’d recommend you to read clojure basics and maybe practicing on 4clojure to internalize the different approach of Clojure.

I hope it can help you solve the problem.