Published in


How to create a case insensitive Bag using Eclipse Collections

Learn how to count Strings in Java without worrying about their case.

HashingStrategyBags in Eclipse Collections allow for a custom HashingStrategy for an object

How can I count strings without regard to case?

A HashBagWithHashingStrategy in Eclipse Collections is easy to construct using the HashingStrategyBags factory. The HashingStrategy in the example above will be based on the Function specified with the method reference String::toLowerCase. We can then add String instances to the MutableBag in strings variable and look up their occurrences without regard to case. The hashCode and equals will be based on converting each String toLowerCase first.

What is a HashingStrategy?

A HashingStrategy is an interface that can be implemented to specify a hashCode and equals implementation for another object. HashingStrategy defines two methods that must be implemented.

public interface HashingStrategy<E>
int computeHashCode(E object);

boolean equals(E object1, E object2);

How can I define a HashingStrategy?

You can build a HashingStrategy from a Function using a factory class named HashingStrategies.

HashingStrategy<String> hashingStrategy = 

This is effectively what the code in the example above does. However, you might want to have more control over the implementation to reduce potential garbage being generated. Another way to implement a case insensitive HashingStrategy that will generate slightly less garbage is as follows.

Creating a HashingStrategyBag using a record implementing the HashingStrategy interface

This HashingStrategy will be more efficient than the one based on Function because it will not convert both String instances toLowerCase in the equals method. Instead the equals method will be based on the equalsIgnoreCase method. I will leave it as an exercise to the reader to implement the computeHashCode in a more optimal manner.

I hope you found this useful. Eclipse Collections also has HashingStrategy based Sets and Maps. You can find out more about these lesser known data structures in the following blog.

Thank you for reading!

I am the creator of and a Committer for the Eclipse Collections OSS project which is managed at the Eclipse Foundation. Eclipse Collections is open for contributions.

Other Java articles you may like



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Donald Raab

Donald Raab

Java Champion. Creator of the Eclipse Collections OSS Java library ( Inspired by Smalltalk. Opinions are my own.