Browse Clojure Foundations for Java Developers

Sets

Unique collections with fast membership tests: create sets, add/remove items, and use clojure.set for union/intersection/difference.

Sets represent unique elements and excel at membership checks. If you’re coming from Java, think HashSet—but persistent and immutable.

Create

1#{:a :b :c}
2(set [1 1 2 3]) ; => #{1 2 3}

Membership

1(def roles #{:admin :billing})
2
3(contains? roles :admin) ; => true
4(roles :admin)           ; => :admin  ; set-as-function membership
5(roles :guest)           ; => nil

Add / Remove

1(conj #{1 2} 3) ; => #{1 2 3}
2(disj #{1 2} 2) ; => #{1}

Adding a duplicate changes nothing:

1(conj #{1 2} 2) ; => #{1 2}

Set Operations (clojure.set)

1(require '[clojure.set :as set])
2
3(set/union #{1 2} #{2 3})        ; => #{1 2 3}
4(set/intersection #{1 2} #{2 3}) ; => #{2}
5(set/difference #{1 2} #{2 3})   ; => #{1}

Knowledge Check: Sets

### What does `(conj #{1 2} 2)` evaluate to? - [x] `#{1 2}` - [ ] `#{1 2 2}` - [ ] It throws because the element is already present. - [ ] `nil` > **Explanation:** Sets enforce uniqueness. Adding an existing element is a no-op (but still returns a set value). ### What does `(#{:a :b} :c)` evaluate to? - [x] `nil` - [ ] `false` - [ ] `:c` - [ ] It throws because sets aren’t callable. > **Explanation:** Sets are callable and perform membership lookup. They return the element when present, otherwise `nil`. ### What does `(set/intersection #{1 2} #{2 3})` evaluate to? - [x] `#{2}` - [ ] `#{1 2 3}` - [ ] `#{1}` - [ ] `[2]` > **Explanation:** Intersection keeps elements present in both sets.
Revised on Friday, April 24, 2026