The Bag Data Structure From Eclipse Collections

In computer science, a bag is defined as an abstract data structure, that allows keeping duplicate elements in any order. This is similar to a physical bag, where you could also put any elements and take them out randomly. So, bags are different from lists (because lists care about a particular position of an element) and from sets (because sets do not allow duplicates). The bag is a good choice when you just need to collect items and do some processing using iterations. Java does not offer its "vanilla" implementation of the bag, however, you could find it in popular collections libraries. In this post, we will review the Bag from Eclipse Collections, which supplies both mutable and immutable versions.

Create Bags

Before we will proceed with various Bag methods, let observe how to initialize a new Bag instance within the Eclipse Collections framework. Likewise to other types of collections, there are presented both mutable (modifiable) and immutable (non-modifiable) versions. In general, we can use the Bags class, which allows utilizing static factory methods to obtain bags:

  • Bags.immutable.* calls ImmutableBagFactory to create immutable bags.
  • Bags.mutable.* calls MutableBagFactory to create mutable bags.

Both types use the same approaches, that can be separated into the following three categories: