Clojure Makes Java Seq-able

The seq abstraction of first/rest applies to anything that there can be more than one of. In the Java world, that includes the following:

  • The Collections API

  • Regular expressions

  • File system traversal

  • XML processing

  • Relational database results

Clojure wraps these Java APIs, making the sequence library available for almost everything you do.

Seq-ing Java Collections

If you try to apply the sequence functions to Java collections, you will find that they behave as sequences. Collections that can act as sequences are called seq-able. For example, arrays are seq-able:

 ​; String.getBytes returns a byte array​
 ​(first (.getBytes "hello"))​
 ​-> 104​
 ​​
 ​(rest (.getBytes "hello"))​
 ​-> (101 108 108 111)​
 ​​
 ​(cons (int ...

Get Programming Clojure, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.