Extending JDK 8 Collections

John McClean
2 min readFeb 2, 2016

cyclops-react adds a series of extensions to standard (mutable) Java collections as well as support for pCollections, a set of persistent collections that also implement the JDK interfaces. See

An Extended List (ListX)

For example to create an extended List we can use the ListX.of (values) or ListX.fromIterable(iterable) creational methods.

ListX implements FluentCollectionX (as well as FluentSequenceX, FluentCollectionX, List & Colleciton). FluentCollectionX adds fluent analogues to JDK manipulation methods such as add / remove - these analogues use plus / minus instead and return ListX so methods can be chained.

Available JDK Extensions

Cyclops provides the following extensions for standard JDK Collections

  1. ListX : javadoc
  2. SetX : javadoc
  3. SortedSetX : javadoc
  4. QueueX : javadoc
  5. DequeX : javadoc

Each CollectionX implementation adds a large array of additional operators to the collection.

Immutable Views

By default JDK extensions are mutable, and are still mutable after each operation is applied. It is possible to construct an immutable view for each collection instead. In the example below the calls to plus and minus result in an UnsupportedOperationException.

We do this by making use of an Immutable Collector instance. Cyclops provides one per collection extension.

Persistent Collections

We’ve also added support for persistent collections, persistent collections are functional data structures that preserve previous versions on ‘update’. This allows more efficient manipulation of immutable collections than standard imperative implementations allow. Cyclops also provides extensions for the pCollections library - from the website.

PCollections serves as a persistent and immutable analogue of the Java Collections Framework. This includes efficient, thread-safe, generic, immutable, and persistent stacks, maps, vectors, sets, and bags, compatible with their Java Collections counterparts.

Available PCollection extensions are

  1. PStackX : javadoc : persistent analogue of JDK LinkedList (implements List)
  2. PVectorX : javadoc : persistent analogue of JDK ArrayList (implements List)
  3. PSetX : javadoc : persistent analogue of JDK Set (implements Set)
  4. POrderedSetX : javadoc : persistent analogue of JDK SortedSet (implements Set)
  5. PBagX : javadoc :unordered persistent colleciton that supports duplicates
  6. PQueueX : javadoc : persisent Queue (implements Queue)

Differences with java.util.stream.Stream

An important difference with Stream is that all operations are applied eagerly. Therefore for long chains of operations converting the extended colllection to a Stream and then converting back will give better performance.

--

--

John McClean

Architecture @ Verizon Media. Maintainer of Cyclops. Twitter @johnmcclean_ie