{"id":17963608,"url":"https://github.com/hellokaton/java-clojure-syntax-comparison","last_synced_at":"2026-03-13T07:33:41.630Z","repository":{"id":86662129,"uuid":"162285803","full_name":"hellokaton/java-clojure-syntax-comparison","owner":"hellokaton","description":"⚔️ Comparison of some code snippets in the Java and Clojure.","archived":false,"fork":false,"pushed_at":"2018-12-19T06:12:56.000Z","size":35,"stargazers_count":9,"open_issues_count":0,"forks_count":2,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-09-07T15:42:29.610Z","etag":null,"topics":["clojure","java-8"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"cc0-1.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hellokaton.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-12-18T12:34:40.000Z","updated_at":"2022-09-18T00:46:32.000Z","dependencies_parsed_at":"2023-11-28T22:30:50.972Z","dependency_job_id":null,"html_url":"https://github.com/hellokaton/java-clojure-syntax-comparison","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/hellokaton/java-clojure-syntax-comparison","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hellokaton%2Fjava-clojure-syntax-comparison","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hellokaton%2Fjava-clojure-syntax-comparison/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hellokaton%2Fjava-clojure-syntax-comparison/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hellokaton%2Fjava-clojure-syntax-comparison/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hellokaton","download_url":"https://codeload.github.com/hellokaton/java-clojure-syntax-comparison/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hellokaton%2Fjava-clojure-syntax-comparison/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30460914,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-13T06:34:02.089Z","status":"ssl_error","status_checked_at":"2026-03-13T06:33:49.182Z","response_time":60,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["clojure","java-8"],"created_at":"2024-10-29T11:42:35.469Z","updated_at":"2026-03-13T07:33:41.614Z","avatar_url":"https://github.com/hellokaton.png","language":null,"readme":"# Java Clojure Syntax Comparison\n\n[![License](https://img.shields.io/badge/license-CC0--1.0-blue.svg)](https://github.com/biezhi/java-clojure-syntax-comparison/blob/master/LICENSE) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com)\n\n\u003e Comparison of some code snippets in the Java and Clojure.\n\n- Java Version: `1.8.0_101`\n- Clojure Version: `1.9.0`\n\n## Contents\n\n### 📍 Basic\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n* [`Hello World`](#hello-world)\n* [`Comment`](#comment)\n* [`Variable`](#variable)\n\n\u003c/details\u003e\n\n### 📚 List\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n* [`Create List`](#create-list)\n* [`Add item`](#add-item-to-list)\n* [`Get item`](#get-list-item)\n* [`Get count`](#get-list-count)\n\n\u003c/details\u003e\n\n### 📚 Array\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n* [`Create Array`](#create-array)\n* [`Get item`](#get-array-item)\n* [`Get count`](#get-array-count)\n* [`Two-dimensional array`](#two-dimensional-array)\n\n\u003c/details\u003e\n\n### 🗺 Map\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n* [`Create Map`](#create-map)\n* [`Get item`](#get-map-item)\n\n\u003c/details\u003e\n\n### 🎛️ Function\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n* [`Define Function`](#define-function)\n* [`Function with parameters`](#function-with-parameters)\n* [`Anonymous function`](#anonymous-function)\n* [`With return value`](#with-return-value)\n* [`Higher-order Function`](#higher-order-function)\n* [`filter`](#filter)\n\n\u003c/details\u003e\n\n### ✈️ Flow Control\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n* [`If Else`](#if-else)\n* [`Switch`](#switch)\n* [`Not`](#not)\n* [`And`](#and)\n* [`Or`](#or)\n* [`For`](#for)\n* [`While`](#while)\n\n\u003c/details\u003e\n\n### 📜 String\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n* [`toString`](#to-string)\n* [`append`](#string-splice)\n* [`replace`](#string-replace)\n* [`join`](#string-join)\n* [`split`](#string-split)\n* [`substring`](#string-substring)\n\n\u003c/details\u003e\n\n### ⏱️ Date\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n* [`Now Time`](#now-time)\n\n\u003c/details\u003e\n\n### ➗ Math\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n* [`average`](#average)\n\n\u003c/details\u003e\n\n### 🔭 IO\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n* [`read-file-as-string`](#read-file-as-string)\n\n\u003c/details\u003e\n\n### ❌ Exception\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n* [`Throw exception`](#throw-exception)\n* [`Try catch`](#try-catch)\n\n\u003c/details\u003e\n\n### ❇️ Thread\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n* [`Create thread`](#create-thread)\n* [`Future`](#future)\n\n\u003c/details\u003e\n\n---\n\n## 📍 Basic\n\n### Hello World\n\nPrint `hello world` is the first thing in programming languages 😋\n\n```java\nSystem.out.print(\"Hello World\\n\");\n\nSystem.out.println(\"Hello World\");\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(print \"Hello World\\n\")\n;; =\u003e Hello World\n\n(println \"Hello World\")\n;; =\u003e Hello World\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### Comment\n\n```java\n// This is a one-line comment\n\n/**\n * This is a multi-line comment\n */\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n; (semicolon) reader macro\n; i don't know what I should do\n\n;; The syntax is like a function: (comment \u0026 body).\n(comment \"\n    Here are the comments\n\")\n\n;; This is used to comment out a form. \n;; a corresponding pair of ( and ), or [ and ]. \n;; The form can be nested.\n(def my-vec #_[1 2 3] [3 4 5])\n;; [1 2 3] was ignored\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### Variable\n\n```java\nString name = \"biezhi\";\nint age     = 2333;\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\nIn fact, variables cannot be defined in `clojure`. These values ​​are immutable, like in Java `final`.\n\n```clojure\n(def name \"biezhi\")\n(def age  2333)\n```\n\n`def` can be creates and interns or locates a global var with the name of symbol.\n\n```clojure\n(def my-number 234)\n;;=\u003e #'user/my-number\n;; what's that returned thing, \"#'user/my-number\" ?\n\n(type #'user/my-number)\n;;=\u003e clojure.lang.Var\n; it is a Var. you just created the Var, at the same time, `my-number` has been bound to 234.\n\nmy-number\n;;=\u003e 234\nuser/my-number\n;;=\u003e 234\n```\n\nIn other languages, a variable assignment looks like `var myvar = \"something\"`, `@myvar = \"something\"`, or `String myVar = \"something\"`.\n\nClojure does things in a different way. First, Clojure doesn’t call it a variable assignment. It is a *var binding*, and this idea is a bit different from assignment in other languages.\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n## 📚 List\n\n### Create List\n\n```java\nList\u003cString\u003e list = new ArrayList\u003c\u003e();\nlist.add(\"a\");\nlist.add(\"b\");\nlist.add(\"c\");\n\nList\u003cString\u003e list = Arrays.asList(\"a\", \"b\", \"c\");\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\nA list uses parentheses as its surrounding delimiters, and so an empty list would look like `()`, whereas a list with three elements could look like `(\"a\" \"b\" \"c\")`.\n\n```clojure\n(def my-list (list \"a\" \"b\" \"c\"))\n\n;; There is a special function called quote that tells Clojure to just treat the\n;; list as data.\n(def my-list (quote (\"a\" \"b\" \"c\")))\n\n;; This syntax is actually more code to type than (list \"a\" \"b\" \"c\"),\n;; so there is a shortcut for the quote function using the ' character\n(def my-list '(\"a\" \"b\" \"c\"))\n```\n\nOne unique thing about lists is that the first element is always evaluated as a function call, with the remaining elements as arguments. So, defining a list just using `()` will cause an error.\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### Add item to List\n\n```java\nlist.add(\"d\");\n\nlist.addAll(newList);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n;; returns a new collection with the xs 'added'\n(conj my-list \"d\")\n;;=\u003e (\"d\" \"a\" \"b\" \"c\")\n\n(cons \"d\" my-list)\n;;=\u003e (\"d\" \"a\" \"b\" \"c\")\n\n(concat my-list '(\"d\" \"e\" \"f\"))\n;;=\u003e (\"a\" \"b\" \"c\" \"d\" \"e\" \"f\")\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### Get List item\n\n```java\nString a = list.get(0);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n;; get first by list\n(first my-list)\n;;=\u003e a\n\n;; get first by list\n(second my-list)\n;;=\u003e b\n\n;; get item by index\n(nth my-list 1)\n;;=\u003e b\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### Get List count\n\n```java\nint size = list.size();\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(count '(1 2 3))\n;;=\u003e 3\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n## 📚 Array\n\n### Create Array\n\n```java\nString[] fruits = new String[3];\nfruits[0] = \"peach\";\nfruits[1] = \"pear\";\nfruits[2] = \"apple\";\n\nString[] fruits = {\"peach\", \"pear\", \"apple\"};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n;; Vector []\n;; A vector looks like an array and is better for random access.\n;; A vector has an index to look up elements at a specific point, speeding up random access\n;; Vectors and maps are the most common data structures use to hold data in Clojure\n\n;; you can use the vector function to create a new vector\n(def fruits (vector \"peach\", \"pear\", \"apple\"))\n\n;; Usually you just use the [] notation to create a vector to help keep your code readable\n(def fruits [\"peach\", \"pear\", \"apple\"])\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### Get Array item\n\n```java\nString pear = fruits[1];\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(second fruits)\n;; =\u003e \"pear\"\n\n(nth fruits 1)\n;; =\u003e \"pear\"\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### Get Array count\n\n```java\nint length = fruits.length;\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(count fruits)\n;;=\u003e 3\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### Two dimensional array\n\n```java\nint[][] points = {\n                {23, 45},\n                {42, 88},\n        };\n\nint[] idx = points[0];\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(def points [[23, 45] [42, 88]])\n\n(first points)\n;;=\u003e [23, 45]\n\n(nth points 1)\n;;=\u003e [42, 88]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n## 🗺 Map\n\n### Create Map\n\n```java\nMap\u003cString, Integer\u003e me = new HashMap\u003c\u003e();\nme.put(\"name\", \"biezhi\");\nme.put(\"age\", 2333);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n;; Map {}\n;; A key / value pair data structure\n;; keys are usually defined as a :keyword, although they can be anything\n\n;; Typicall a :keyword is used for a the key in a map, with the value being\n;; a string, number or another keyword\n(def me {:name \"biezhi\",\n         :age   2333\n         :url   \"https://github.com/biezhi\"})\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### Get Map item\n\n```java\nme.get(\"url\");\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(:name me)\n;;=\u003e \"biezhi\"\n\n(get me :name)\n;;=\u003e \"biezhi\"\n\n(me :name)\n;;=\u003e \"biezhi\"\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n## 🎛️ Function\n\n### Define function\n\n```java\nvoid sayHello() {\n    System.out.println(\"hello\");\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n;; assign a function to a variable\n(defn say-hello [] (println \"hello\"))\n\n(say-hello)\n;; =\u003e hello\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### Function with parameters\n\n```java\nvoid sayHello(String name) {\n    System.out.println(\"hello \" + name);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n;; define a function with parameters\n(defn say-hello [name] (println (str \"hello \" name)))\n\n(say-hello \"world\")\n;; =\u003e hello world\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### Anonymous function\n\n```java\nRunnable task = () -\u003e System.out.println(\"Hello Boy.\");\ntask.run();\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(def say-hello\n  (fn []\n    (str \"hello world\")))\n\n;; assign a function to a variable\n(def say-hello\n (fn [name]\n   (str \"Hello \" name)))\n\n;; the same but using an anonymous function\n(def say-hello\n #(str \"hello \" %))\n\n;; anonymous function using two arguments\n(def hello-doc #(str \"Hello \" %1 %2))\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### With return value\n\n```java\nString sayHello(String name) {\n    return \"hello \" + name;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(defn say-hello [name] (str \"hello \" name))\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### Higher-order function\n\n```java\npublic void onConsumer(Consumer\u003cString\u003e consumer) {\n    consumer.accept(\"let's go\");\n}\n   \npublic Function\u003cString, Integer\u003e myConvert(){\n    return Integer::parseInt;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\nA higher-order function is:\n\n- a function that takes one or more functions as arguments\n- or a function that returns a function\n\nIn other languages, this feature may have another name. For example, Ruby names it block for a callee function, although the caller doesn’t have specific name.\n\nIn Clojure, caller functions are high-order functions while callees don’t have specific names. Some well known higher-order functions are `map`, `reduce`, `remove`, `filter`, and `iterate`. \n\n```clojure\n(defn on-consumer [fn] (fn \"let's go\"))\n(on-consumer str)\n;;=\u003e \"let's go\"\n\n(defn my-convert [str] (Integer. str))\n(my-convert \"123\")\n;;=\u003e 123\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### filter\n\n```java\nlong count = IntStream.of(3, 5, 10, 2, 29, 1, 24, 13)\n                      .filter(i -\u003e i \u003c 10)\n                      .count();\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\nThe `filter` function is a commonly-used `higher-order functions`. It takes a function as an argument. The `filter` function works as its name implies. It filters out values in a sequence that don’t meet the given condition. To perform this filtering, `filter` takes a function and a sequence for its arguments. The function given to the `filter` must return a truthy value, and is called a predicate function.\n\nThe syntax is: `(filter pred coll)`\n\n```clojure\n(filter #(\u003c % 10) [3 5 10 2 29 1 24 13])\n;;=\u003e (3 5 2 1)\n\n(count (filter #(\u003c % 10) [3 5 10 2 29 1 24 13]))\n;;=\u003e 4\n\n(filter odd? (range 10))\n;;=\u003e (1 3 5 7 9)\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n## ✈️ Flow Control\n\n### If else\n\n```java\nint age = 23;\nif (age \u003e 18) {\n    System.out.println(\"You have grown up, don't be like a child again.\");\n} else {\n    System.out.println(\"Let's learn the cat call together, say 'miao miao miao'.\");\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n“If it is a good weather, I will go to a park; otherwise, I’ll go to a cafe.” This is called “if-branching” in the programming world. Since the if-branching uses simple conditionals, it is frequently used to divide into two states: true or false.\n\nIn Clojure, `if` is a special form. The syntax is:\n\n```clojure\n(if test then else?) or (if test then)\n```\n\n```clojure\n(def age 14)\n(if (\u003e age 18)\n  (println \"You have grown up, don't be like a child again.\")\n  (println \"Let's learn the cat call together, say 'miao miao miao'.\"))\n```\n\nIn addition, Clojure has a unique way of using the `if` conditional with the `let` binding. It is `if-let` macro, which is useful when we want to use the result of *test*.\n\nThe syntax is:\n\n```clojure\n(if-let bindings then) or (if-let bindings then else \u0026 oldform)\n```\n\n```clojure\n(defn weather-is-good?\n        [weather]\n        (if-let [actual (= :good weather)]\n                (str \"The weather is good? \" actual)\n                \"The weather is at least not good.\"))\n\n(weather-is-good? :good)\n;;=\u003e \"The weather is good? true\"\n\n(weather-is-good? :bad)\n;;=\u003e \"The weather is at least not good.\"\n```\n\n\u003c/details\u003e\n\n---\n\n```java\nint temp = 10;\nif (temp \u003e 65) {\n    System.out.println(\"I'll enjoy walking at a park.\");\n} else if (temp \u003e 45) {\n    System.out.println(\"I'll spend time at a cafe.\");\n} else {\n    System.out.println(\"I'll curl up in my bed.\");\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(defn what-to-do\n        [temp]\n        (cond\n         (\u003e temp 65) \"I'll enjoy walking at a park.\"\n         (\u003e temp 45) \"I'll spend time at a cafe.\"\n         :else \"I'll curl up in my bed.\"))\n\n(what-to-do 70)\n;;=\u003e \"I'll enjoy walking at a park.\"\n\n(what-to-do 50)\n;;=\u003e \"I'll spend time at a cafe.\"\n\n(what-to-do 30)\n;;=\u003e \"I'll curl up in my bed.\"\n```\n\nClojure has `condp` macro also. The usage is similar to `cond`, but it takes a part of test right after the condp.\n\nThe syntax is: `(condp pred expr \u0026 clauses)`\n\n```clojure\n(defn what-to-do-p\n        [temp]\n        (condp \u003c temp\n               65 \"I'll enjoy walking at a park.\"\n               45 \"I'll spend time at a cafe.\"\n               \"I'll curl up in my bed\"))\n\n(what-to-do-p 70)\n;;=\u003e \"I'll enjoy walking at a park.\"\n\n(what-to-do-p 50)\n;;=\u003e \"I'll spend time at a cafe.\"\n\n(what-to-do-p 30)\n;;=\u003e \"I'll curl up in my bed.\"\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### Switch\n\n```java\nint color = 3;\nswitch(color) {\n    case 3:\n        return \"red\";\n    case 2:\n        return \"blue\";\n    case 1:\n        return \"pink\";\n    default:\n        return \"#000\";\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\nThe `case` macro is a similar conditional to `cond/condp`. It branches to multiple clauses. The difference is that `case` doesn’t evaluate branching expressions. In `case`, it should be a constant. What we can do with `case` looks like `map (data structure)`.\n\nThe syntax is: `(case e \u0026 clauses)`\n\n```clojure\n(case 3\n  3 \"red\"\n  2 \"blue\"\n  1 \"pink\"\n  \"#000\")\n;;=\u003e \"red\"\n\n(defn cases-to-do [temp]\n  (case temp\n        :65-80 \"I'll enjoy walking at a park.\"\n        :45-64 \"I'll spend time at a cafe.\"\n        \"I'll curl up in my bed\"))\n\n(cases-to-do :65-80)\n;;=\u003e \"I'll enjoy walking at a park.\"\n\n(my-cases :45-64)\n;;=\u003e \"I'll spend time at a cafe.\"\n\n(my-cases :other)\n;;=\u003e \"I'll curl up in my bed\"\n\n; hash-map can't take a key that doesn't match anything\n(my-cases :30) \n;;=\u003e nil\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### Not\n\n```java\nint flag = 2333;\n\nif (flag != 100){\n    // do some thing\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(def flag 2333)\n(if (not (= 100 flag)) (println \"not eq 2333\"))\n;;=\u003e not eq 2333\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### And\n\n```java\nboolean success = (result.ok \u0026\u0026 result.code == 200);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(and (true? result.ok) (= 200 result.code))\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### Or\n\n```java\nboolean success = (result.ok || result.code == 200);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(or (true? result.ok) (= 200 result.code))\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### For\n\n```java\nfor (int i=0; i\u003c10; i++){\n    System.out.println(\"i = \" + i);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\nThe *for loop* is a common concept in computer languages. When we want to apply the same logic (operations) to each element of a given array (vector or list in Clojure), we apply the idea of a *for loop* to that. In general, this involves incrementing (or decrementing) an index and performing a similar function on each element. However, the way to implement a for loop varies from language to language. Some use an index variable explicitly. Others use an iterator. Some use neither. Clojure takes a very different approach. \n\nClojure’s `for` is categorized as a sequence operator, like `map`(core function) or `reduce`. More importantly, in Clojure, `for` is used for *list comprehension*, which means it creates a list from a given `list`. \n\nThe syntax of the `for` macro is: `(for [binding-form coll-expr filter-expr?] expr)`\n\n```clojure\n(for [i (range 10)] \n  (do (println (str \"i =\" i))))\n\n(for [w [\"LOVe\" \"coding\" \"hEllo\" \"worLD!\"]]\n           (clojure.string/capitalize w))\n; like let, *for* takes binding-form\n;;=\u003e (\"Love\" \"Coding\" \"Hello\" \"World!\")\n\n; we can get the same result using the *map* core function\n(map clojure.string/capitalize [\"LOVe\" \"coding\" \"hEllo\" \"worLD!\"])\n;;=\u003e (\"Love\" \"Coding\" \"Hello\" \"World!\")\n\n; include only when length of the word exceeds 5\n(for [w [\"LOVe\" \"coding\" \"hEllo\" \"worLD!\"] :when (\u003e (count w) 5)]\n           (clojure.string/capitalize w))\n;;=\u003e (\"Coding\" \"World!\")\n\n; using let binding\n(for [w [\"LOVe\" \"coding\" \"hEllo\" \"worLD!\"] :let [length (count w)]]\n           (str (clojure.string/capitalize w) \": \" length))\n;;=\u003e (\"Love: 4\" \"Coding: 6\" \"Hello: 5\" \"World!: 6\")\n\n; when the input consists of multiple vectors\n(for [x [\"a\" \"b\" \"c\"]\n      y [\"a\" \"b\" \"c\"]\n      z [\"a\" \"b\" \"c\"]]\n     (str x y z))\n;;=\u003e (\"aaa\" \"aab\" \"aac\" \"aba\" \"abb\" \"abc\" \"aca\" \"acb\" \"acc\" \"baa\" \"bab\" \"bac\" \"bba\" \"bbb\" \"bbc\" \"bca\" \"bcb\" \"bcc\" \"caa\" \"cab\" \"cac\" \"cba\" \"cbb\" \"cbc\" \"cca\" \"ccb\" \"ccc\")\n```\n\n\u003c/details\u003e\n\n```java\nString someJoin(String[] coll, String result) {\n    if (coll.length == 1) {\n        return result + coll[0];\n    }\n    StringBuilder sbuf = new StringBuilder();\n    for (String str : coll) {\n        sbuf.append(str).append(\", \");\n    }\n    return sbuf.substring(0, sbuf.length() - 2);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\nWhile `for` is somewhat like a loop, `recur` is a real loop in Clojure. `recur` represents such a remarkable idea that we might even say, “this *is* Clojure.”\n\nIf you have a programming background, you may have heard of tail *recursion*, which is a major feature of functional languages. This `recur` special form is the one that implements *tail recursion*. As the words “*tail recursion*” indicate, recur must be called in the tail position. In other words, `recur` must be the last thing to be evaluated. \n\nThe syntax of the recur macro is: `(recur exprs*)`\n\n```clojure\n(defn some-join [coll result]\n        (if (= 1 (count coll)) (str result (first coll))\n          (recur (rest coll) (str result (first coll) \", \"))))\n\n(some-join [\"hello\" \"world\" \"love\" \"coding\"] \"Words: \")\n;;=\u003e \"Words: hello, world, love, coding\"\n\n; when we want to do something just before the recur\n; we can use *do*\n(defn some-join [coll result]\n      (if (= 1 (count coll)) (str result (first coll))\n        (do\n          (println result)\n          (recur (rest coll) (str result (first coll) \", \")))))\n\n(some-join [\"hello\" \"world\" \"love\" \"coding\"] \"Words: \")\n;;=\u003e Words:\n;;=\u003e Words: hello,\n;;=\u003e Words: hello, world,\n;;=\u003e \"Words: hello, world, love, coding\"\n\n; however, just for printing out the process, let binding works\n(defn some-join [coll result]\n  (let [_ (println result)]\n    (if (= 1 (count coll)) (str result (first coll))\n      (recur (rest coll) (str result (first coll) \", \")))))\n\n(some-join [\"hello\" \"world\" \"love\" \"coding\"] \"Words: \")\n;;=\u003e Words:\n;;=\u003e Words: hello,\n;;=\u003e Words: hello, world,\n;;=\u003e Words: hello, world, love,\n;;=\u003e \"Words: hello, world, love, coding\"\n\n; we attempted the same thing as clojure.string/join function does\n(str \"Words: \" (clojure.string/join \", \" [\"hello\" \"world\" \"love\" \"coding\"]))\n;;=\u003e \"Words: hello, world, love, coding\"\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### While\n\n```java\nint seq = 10;\nwhile (seq \u003e 0) {\n    System.out.prinln(\"seq = \" + (seq--));\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(def seq-num (atom 10))\n(while (\u003e @seq-num 0)\n   (do (println (str \"seq = \" @seq-num)) (swap! seq-num dec) ))\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n## 📜 String\n\n### to string\n\n```java\nInteger age = 2333;\nSystem.out.println(age.toString());\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(str 2333)\n;;=\u003e \"2333\"\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### String append\n\n```java\nString a = \"hello \" + \"world \" + 2333;\n```\n\n`str` is a function that turns its arguments into strings.\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(str \"hello \" \"world \" 2333)\n;;=\u003e \"hello world 2333\"\n\n(str :a-keyword)\n;;=\u003e \":a-keyword\"\n\n(str false)\n;;=\u003e \"false\"\n\n(map str (range 10))\n;;=\u003e (\"0\" \"1\" \"2\" \"3\" \"4\" \"5\" \"6\" \"7\" \"8\" \"9\")\n```\n\nWhen `str` is given multiple arguments, then it will concatenate them all into one big string.\n\n```clojure\n(str \"I need \" 5 \" of these\")\n;;=\u003e \"I need 5 of these\"\n\n(str \"In \"\n     (rand-nth [\"summer\" \"winter\"])\n     \" I like to go \"\n     (rand-nth [\"swimming\" \"running\"]))\n;;=\u003e \"In summer I like to go swimming\"\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### String replace\n\n```java\nString url = \"https://biezhi.me\";\nSystem.out.println(\"New url is: \" + url.replace('.', '#');\n\nString str = \"A good day to you, sir.  Good day.\";\nSystem.out.println(\"New str is: \" + url.replaceFirst(\"day\", \"night\");\n\nString str = \"This is a String to use as an example to present raplaceAll\";\nSystem.out.println(str.replaceAll(\"This\", \"That\"));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(clojure.string/replace \"https://biezhi.me\" #\"\\.\" \"#\")\n\n;; replace with Java method\n(.replace \"https://biezhi.me\" \".\" \"#\")\n\n;; Only replace the first match.\n(clojure.string/replace-first \"A good day to you, sir.  Good day.\" #\"day\" \"night\")\n;;=\u003e \"A good night to you, sir.  Good day.\"\n\n;; If there are no matches, return the original string.\n(clojure.string/replace-first \"A good day to you, sir.\" #\"madam\" \"master\")\n;;=\u003e \"A good day to you, sir.\"\n\n;; To title case\n(clojure.string/replace \"hello world\" #\"\\b.\" #(.toUpperCase %1))\n;;=\u003e \"Hello World\"\n\n;; replaces all a's with 1 and all b's with 2\n(clojure.string/replace \"a b a\" #\"a|b\" {\"a\" \"1\" \"b\" \"2\"})\n;=\u003e \"1 2 1\"\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### String join\n\n```java\nString.join(\", \", \"jack\", \"biezhi\", \"rose\", \"mark\")\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(clojure.string/join \", \" [\"jack\", \"biezhi\", \"rose\", \"mark\"])\n;;=\u003e \"jack, biezhi, rose, mark\"\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### String split\n\n```java\n\"jack, biezhi, rose, mark\".split(\", \");\n\n\"h1e2l3l4o5w6o7r8d9d\".split(\"\\\\d+\");\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(clojure.string/split \"jack, biezhi, rose, mark\" #\", \")\n;;=\u003e [\"jack\" \"biezhi\" \"rose\" \"mark\"]\n\n(clojure.string/split \"h1e2l3l4o5w6o7r8d9d\" #\"\\d+\")\n;;=\u003e [\"h\" \"e\" \"l\" \"l\" \"o\" \"w\" \"o\" \"r\" \"d\" \"d\"]\n\n;; Note that the 'limit' arg is the maximum number of strings to\n;; return (not the number of splits)\n(clojure.string/split \"q1w2e3r4t5y6u7i8o9p0\" #\"\\d+\" 5)\n;;=\u003e [\"q\" \"w\" \"e\" \"r\" \"t5y6u7i8o9p0\"]\n\n;; to get back all the characters of a string, as a vector of strings:\n(clojure.string/split \" q1w2 \" #\"\")\n;;=\u003e [\" \" \"q\" \"1\" \"w\" \"2\" \" \"]\n\n;; Note: sequence, in contrast, would return characters.\n;; Using lookarounds (lookahead, lookbehind) one can keep the matching characters:\n(clojure.string/split \" something and ACamelName \" #\"(?=[A-Z])\")\n;;=\u003e [\" something and \" \"A\" \"Camel\" \"Name \"]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n### String substring\n\n```java\n\"biezhi\".substring(1);\n\"biezhi\".substring(0, 3);\n\"biezhi\".substring(0, 6);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eClojure\u003c/summary\u003e\n\n```clojure\n(subs \"biezhi\" 1)\n;;=\u003e \"iezhi\"\n\n(subs \"biezhi\" 0 3)\n;;=\u003e \"bie\"\n\n(subs \"biezhi\" 0 6)\n;;=\u003e \"biezhi\"\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#contents)\n\n# Clojure Links\n\n- [clojure-through-code](https://github.com/practicalli/clojure-through-code)\n- [clojure docs](https://clojuredocs.org/quickref)\n- [learn clojure](https://hackr.io/tutorials/learn-clojure)\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhellokaton%2Fjava-clojure-syntax-comparison","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhellokaton%2Fjava-clojure-syntax-comparison","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhellokaton%2Fjava-clojure-syntax-comparison/lists"}