select first item of a collection that satisfies given predicate in clojure

There are multiple possibilities.

some

some returns the first non-nil value its predicate returns.

(some #(when (> % 10) %) (range)) ;; => 11

filter + first

filter retains those elements that match a predicate, first retrieves the first of them.

(first (filter #(> % 10) (range))) ;; => 11

remove + first

If you want to find the first element that does not match your predicate, remove is your friend:

(first (remove #(<= % 10) (range))) ;; => 11

Or with some:

(some #(when-not (<= % 10) %) (range)) ;; => 11

So, that's it, I guess.


Use filter and first

user=> (->> (range) (filter #(> % 10)) first)
11
user=> (first (filter #(> % 10) (range)))
11

Tags:

Clojure