How to create a case insensitive Bag using Eclipse Collections
Learn how to count Strings in Java without worrying about their case.
How can I count strings without regard to case?
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
strings variable and look up their occurrences without regard to case. The
equals will be based on converting each
What is a HashingStrategy?
HashingStrategy is an interface that can be implemented to specify a
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
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.
HashingStrategy will be more efficient than the one based on
Function because it will not convert both
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
Maps. You can find out more about these lesser known data structures in the following blog.
The missing Java data structures no one ever told you about — Part 1
Eclipse Collections provides additional collection types not found in the JDK.
Thank you for reading!
Other Java articles you may like
The 2022 Java Programmer RoadMap
An illustrated guide to becoming a Java Developer in 2022 with links to relevant courses
Top 50 Data Structure and Algorithms Interview Questions for Programmers
Preparing for Programming job interviews? Here are 50+ Data Structure and algorithms problems you can practice to…