The new Certification Class of REST With Spring is out:

>> CHECK OUT THE COURSE

1. Overview

Eclipse Collections is another improved collection framework for Java.

Simply put, it provides optimized implementations as well as some additional data structures and features which are not found in the core Java.

The library provides both mutable and immutable implementations of all data structures.

2. Maven Dependency

Let’s start by adding the following Maven dependency to our pom.xml:

<dependency
    <groupId>org.eclipse.collections</groupId>
    <artifactId>eclipse-collections</artifactId>
    <version>8.2.0</version>
</dependency>

We can find the latest version of the library in the Maven Central Repository.

3. The Big Picture

3.1. Basic Collection Types

Basic collection types in Eclipse Collections are:

  • ListIterable – an ordered collection that maintains insertion order and allows duplicate elements. Subinterfaces include: MutableListFixedSizeList and ImmutableList. The most common ListIterable implementation is FastList, which is a subclass of MutableList
  • SetIterable – a collection that allows no duplicate elements. It can be sorted or unsorted. Subinterfaces include: SortedSetIterable and UnsortedSetIterable. The most common unsorted SetIterable implementation is UnifiedSet
  • MapIterable – a collection of key/value pairs. Subinterfaces include MutableMapFixedSizeMap and ImmutableMap. Two common implementations are UnifiedMap and MutableSortedMap. While UnifiedMap does not maintain any order, MutableSortedMap maintains the natural order of elements
  • BiMap – a collection of key/value pairs that can be iterated through in either direction. BiMap extends the MapIterable interface
  • Bag – an unordered collection that allows duplicates. Subinterfaces include MutableBag and FixedSizeBag. The most common implementation is HashBag
  • StackIterable – a collection that maintains “last-in, first-out” order, iterating through elements in reverse insertion order. Subinterfaces include MutableStack and ImmutableStack
  • MultiMap – a collection of key/value pairs that allows multiple values for each key

3.2. Primitive Collections

The framework also provides a huge set of primitive collections; their implementations are named after the type they hold. There are mutable, immutable, synchronized and unmodifiable forms for each type of them:

  • Primitive Lists
  • Primitive Sets
  • Primitive Stacks
  • Primitive Bags
  • Primitive Maps
  • IntInterval

There is a huge number of primitive map forms covering all possible combinations of either primitive or object keys and either primitive or object values.

A quick note – an IntInterval is a range of integers that may be iterated over using a step value.

4. Instantiating a Collection

To add elements to an ArrayList or HashSet, we instantiate a collection by calling the no-arg constructor and then adding each element one by one.

While we can still do that in Eclipse Collections, we can also instantiate a collection and provide all initial elements at the same time in a single line.

Let’s see how we can instantiate a FastList:

MutableList<String> list = FastList.newListWith(
  "Porsche", "Volkswagen", "Toyota", "Mercedes", "Toyota");

Similarly, we can instantiate a UnifiedSet and add elements to it by passing the elements to the newSetWith() static method:

Set<String> comparison = UnifiedSet.newSetWith(
  "Porsche", "Volkswagen", "Toyota", "Mercedes");

Here’s how we can instantiate a HashBag:

MutableBag<String> bag = HashBag.newBagWith(
  "Porsche", "Volkswagen", "Toyota", "Porsche", "Mercedes");

Instantiating maps and adding key and value pairs to them is similar. The only difference is that we pass the key and value pairs to the newMapWith() method as implementations of the Pair interface.

Let’s take UnifiedMap as an example:

Pair<Integer, String> pair1 = Tuples.pair(1, "One");
Pair<Integer, String> pair2 = Tuples.pair(2, "Two");
Pair<Integer, String> pair3 = Tuples.pair(3, "Three");

UnifiedMap<Integer, String> map = new UnifiedMap<>(pair1, pair2, pair3);

We can still use the Java Collections API approach:

UnifiedMap<Integer, String> map = new UnifiedMap<>();

map.put(1, "one");
map.put(2, "two");
map.put(3, "three");

Since immutable collections cannot be modified, they do not have implementations of methods that modify collections such as add() and remove().

Unmodifiable collections, however, allow us to call these methods but will throw an UnsupportedOperationException if we do.

5. Retrieving Elements from Collections

Just like using standard Lists, elements of Eclipse Collections Lists can be retrieved by their index:

list.get(0);

And values of Eclipse Collections maps can be retrieved using their key:

map.get(0);

The getFirst() and getLast() methods can be used to retrieve first and last elements of a list respectively. In the case of other collections, they return the first and the last element that would be returned by an iterator.

map.getFirst();
map.getLast();

The methods max() and min() can be used to get the maximum and minimum values of a collection based on the natural ordering.

map.max();
map.min();

6. Iterating over a Collection

Eclipse Collections provides many ways for iterating over collections. Let’s see what they are and how they work in practice.

6.1. Collection Filtering

The select pattern returns a new collection containing elements of a collection that satisfy a logical condition. It is essentially a filtering operation.

Here’s an example:

@Test
public void givenListwhenSelect_thenCorrect() {
    MutableList<Integer> greaterThanThirty = list
      .select(Predicates.greaterThan(30))
      .sortThis();
    
    Assertions.assertThat(greaterThanThirty)
      .containsExactly(31, 38, 41);
}

The same thing can be done using a simple lambda expression:

return list.select(i -> i > 30)
  .sortThis();

The reject pattern is the opposite. It returns a collection of all the elements that do not satisfy a logical condition.

Let’s see an example:

@Test
public void whenReject_thenCorrect() {
    MutableList<Integer> notGreaterThanThirty = list
      .reject(Predicates.greaterThan(30))
      .sortThis();
    
    Assertions.assertThat(notGreaterThanThirty)
      .containsExactlyElementsOf(this.expectedList);
}

Here, we reject all elements that are greater than 30.

6.2. The collect() Method

The collect method returns a new collection whose elements are the results returned by the provided lambda expression – essentially it’s a combination of the map() and collect() from Stream API.

Let’s see it in action:

@Test
public void whenCollect_thenCorrect() {
    Student student1 = new Student("John", "Hopkins");
    Student student2 = new Student("George", "Adams");
    
    MutableList<Student> students = FastList
      .newListWith(student1, student2);
    
    MutableList<String> lastNames = students
      .collect(Student::getLastName);
    
    Assertions.assertThat(lastNames)
      .containsExactly("Hopkins", "Adams");
}

The created collection lastNames contains the last names which are collected from the students list.

But, what if the returned collection is a collection of collections and we do not want to maintain a nested structure?

For example, if each student has multiple addresses, and we need a collection that contains the addresses as Strings rather than a collection of collections, we can use the flatCollect() method.

Here’s an example:

@Test
public void whenFlatCollect_thenCorrect() {
    MutableList<String> addresses = students
      .flatCollect(Student::getAddresses);
    
    Assertions.assertThat(addresses)
      .containsExactlyElementsOf(this.expectedAddresses);
}

6.3. Element Detection

The detect method finds and returns the first element that satisfies a logical condition.

Let’s go over a quick example:

@Test
public void whenDetect_thenCorrect() {
    Integer result = list.detect(Predicates.greaterThan(30));
    
    Assertions.assertThat(result)
      .isEqualTo(41);
}

The anySatisfy method determines whether any element of a collection satisfies a logical condition.

Here’s an example:

@Test
public void whenAnySatisfiesCondition_thenCorrect() {
    boolean result = list.anySatisfy(Predicates.greaterThan(30));
    
    assertTrue(result);
}

Similarly, the allSatisfy method determines whether all elements of a collection satisfy a logical condition.

Let’s see a quick example:

@Test
public void whenAnySatisfiesCondition_thenCorrect() {
    boolean result = list.allSatisfy(Predicates.greaterThan(0));
    
    assertTrue(result);
}

6.4. The partition() Method

The partition method allocates each element of a collection into one of two collections depending on whether or not the element satisfies a logical condition.

Let’s see an example:

@Test
public void whenAnySatisfiesCondition_thenCorrect() {
    MutableList<Integer> numbers = list;
    PartitionMutableList<Integer> partitionedFolks = numbers
      .partition(i -> i > 30);
	
    MutableList<Integer> greaterThanThirty = partitionedFolks
      .getSelected()
      .sortThis();
    MutableList<Integer> smallerThanThirty = partitionedFolks
      .getRejected()
      .sortThis();
    
    Assertions.assertThat(smallerThanThirty)
      .containsExactly(1, 5, 8, 17, 23);
    Assertions.assertThat(greaterThanThirty)
      .containsExactly(31, 38, 41);
}

6.5. Lazy Iteration

Lazy iteration is an optimization pattern in which an iteration method is invoked, but its actual execution is deferred until its action or return values are required by another subsequent method.

@Test
public void whenLazyIteration_thenCorrect() {
    Student student1 = new Student("John", "Hopkins");
    Student student2 = new Student("George", "Adams");
    Student student3 = new Student("Jennifer", "Rodriguez");

    MutableList<Student> students = Lists.mutable
      .with(student1, student2, student3);
    LazyIterable<Student> lazyStudents = students.asLazy();
    LazyIterable<String> lastNames = lazyStudents
      .collect(Student::getLastName);
    
    Assertions.assertThat(lastNames)
      .containsAll(Lists.mutable.with("Hopkins", "Adams", "Rodriguez"));
}

Here, the lazyStudents object does not retrieve the elements of the students list until the collect() method is called.

7. Pairing Collection Elements

The method zip() returns a new collection by combining elements of two collections into pairs. If any of the two collections is longer, the remaining elements will be truncated.

Let’s see how we can use it:

@Test
public void whenZip_thenCorrect() {
    MutableList<String> numbers = Lists.mutable
      .with("1", "2", "3", "Ignored");
    MutableList<String> cars = Lists.mutable
      .with("Porsche", "Volvo", "Toyota");
    MutableList<Pair<String, String>> pairs = numbers.zip(cars);
    
    Assertions.assertThat(pairs)
      .containsExactlyElementsOf(this.expectedPairs);
}

We can also pair a collection’s elements with their indexes using the zipWithIndex() method:

@Test
public void whenZip_thenCorrect() {
    MutableList<String> cars = FastList
      .newListWith("Porsche", "Volvo", "Toyota");
    MutableList<Pair<String, Integer>> pairs = cars.zipWithIndex();
    
    Assertions.assertThat(pairs)
      .containsExactlyElementsOf(this.expectedPairs);
}

8. Converting Collections

Eclipse Collections provides simple methods for converting a container type to another. These methods are toList(), toSet(), toBag() and toMap().

Let’s see how we can use them:

public static List convertToList() {
    UnifiedSet<String> cars = new UnifiedSet<>();
    
    cars.add("Toyota");
    cars.add("Mercedes");
    cars.add("Volkswagen");
    
    return cars.toList();
}

Let’s run our test:

@Test
public void whenConvertContainerToAnother_thenCorrect() {
    MutableList<String> cars = (MutableList) ConvertContainerToAnother 
      .convertToList();
    
    Assertions.assertThat(cars)
      .containsExactlyElementsOf(
      FastList.newListWith("Volkswagen", "Toyota", "Mercedes"));
}

9. Conclusion

In this tutorial, we’ve seen a quick overview of Eclipse Collections and the features they provide.

The full implementation of this tutorial is available over on GitHub.

Go deeper into building a REST API with Spring:

>> CHECK OUT THE COURSE

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz