Class CaseInsensitiveSet<E>
- Type Parameters:
E- the type of elements maintained by this set
- All Implemented Interfaces:
Serializable,Iterable<E>,Collection<E>,Set<E>
Set implementation that performs case-insensitive comparisons for String elements,
while preserving the original case of the strings. This set can contain both String and non-String elements,
providing support for homogeneous and heterogeneous collections.
Key Features
- Case-Insensitive String Handling: For
Stringelements, comparisons are performed in a case-insensitive manner, but the original case is preserved when iterating or retrieving elements. - Homogeneous and Heterogeneous Collections: Supports mixed types within the set, treating non-String
elements as in a normal
Set. - Customizable Backing Map: Allows specifying the underlying
Mapimplementation, providing flexibility for use cases requiring custom performance or ordering guarantees. - Compatibility with Java Collections Framework: Fully implements the
Setinterface, supporting standard operations likeadd(),remove(), andretainAll(). - Thread Safety: Thread safety depends on the backing map implementation. When backed by
concurrent maps (e.g.,
ConcurrentHashMap), the set is thread-safe.
Usage Examples
// Create a case-insensitive set
CaseInsensitiveSet<String> set = new CaseInsensitiveSet<>();
set.add("Hello");
set.add("HELLO"); // No effect, as "Hello" already exists
LOG.info(set); // Outputs: [Hello]
// Mixed types in the set
CaseInsensitiveSet<Object> mixedSet = new CaseInsensitiveSet<>();
mixedSet.add("Apple");
mixedSet.add(123);
mixedSet.add("apple"); // No effect, as "Apple" already exists
LOG.info(mixedSet); // Outputs: [Apple, 123]
Backing Map Selection
The backing map for this set can be customized using various constructors:
- The default constructor uses a
CaseInsensitiveMapwith aLinkedHashMapbacking to preserve insertion order. - Other constructors allow specifying the backing map explicitly or initializing the set from another collection.
Thread Safety
Thread safety depends entirely on the thread safety of the chosen backing map:
- Thread-Safe: When backed by concurrent maps (
ConcurrentHashMap,ConcurrentSkipListMap,ConcurrentHashMapNullSafe,ConcurrentNavigableMapNullSafe), all operations are thread-safe. - Not Thread-Safe: When backed by non-concurrent maps (
LinkedHashMap,HashMap,TreeMap), external synchronization is required for thread safety.
Implementation Note
This implementation uses Collections.newSetFromMap(Map) internally to create a Set view over
a CaseInsensitiveMap. This provides a clean, efficient implementation that leverages the
proven JDK Collections framework while maintaining case-insensitive semantics for String elements.
Deprecated Methods
The following methods are deprecated and retained for backward compatibility:
plus(): UseaddAll(Collection)instead.minus(): UseremoveAll(Collection)instead.
- Author:
- John DeRegnaucourt ([email protected])
Copyright (c) Cedar Software LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
License
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - See Also:
-
Constructor Summary
ConstructorsConstructorDescriptionConstructs an emptyCaseInsensitiveSetbacked by aCaseInsensitiveMapwith a defaultLinkedHashMapimplementation.CaseInsensitiveSet(int initialCapacity) Constructs an emptyCaseInsensitiveSetwith the specified initial capacity.CaseInsensitiveSet(int initialCapacity, float loadFactor) Constructs an emptyCaseInsensitiveSetwith the specified initial capacity and load factor.CaseInsensitiveSet(Collection<? extends E> collection) Constructs aCaseInsensitiveSetcontaining the elements of the specified collection.CaseInsensitiveSet(Collection<? extends E> source, Map backingMap) Constructs aCaseInsensitiveSetcontaining the elements of the specified collection, using the provided map as the backing implementation. -
Method Summary
Modifier and TypeMethodDescriptionbooleanbooleanaddAll(Collection<? extends E> c) voidclear()booleanbooleancontainsAll(Collection<?> c) longReturns an estimate of the number of elements in this set when backed by a ConcurrentHashMap.booleanvoidPerforms the given action for each element in this set, with operations potentially performed in parallel when the parallelism threshold is met and the set is backed by a ConcurrentHashMap.voidPerforms the given action for each element of the set until all elements have been processed or the action throws an exception.Returns the underlying map used to implement this set.inthashCode()booleanisEmpty()iterator()Deprecated.Deprecated.UseremoveAll(Collection)insteadDeprecated.UseaddAll(Collection)insteadDeprecated.Useadd(Object)instead<U> UreduceElements(long parallelismThreshold, Function<? super E, ? extends U> transformer, BiFunction<? super U, ? super U, ? extends U> reducer) Returns the result of accumulating all elements in this set using the given reducer and transformer functions.booleanbooleanremoveAll(Collection<?> c) booleanRemoves all of the elements of this collection that satisfy the given predicate.booleanretainAll(Collection<?> c) <U> UsearchElements(long parallelismThreshold, Function<? super E, ? extends U> searchFunction) Returns a non-null result from applying the given search function to each element in this set, or null if none are found.intsize()Creates aSpliteratorover the elements in this set.Object[]toArray()<T> T[]toArray(T[] a) toString()Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, waitMethods inherited from interface java.util.Collection
parallelStream, stream, toArray
-
Constructor Details
-
CaseInsensitiveSet
public CaseInsensitiveSet()Constructs an emptyCaseInsensitiveSetbacked by aCaseInsensitiveMapwith a defaultLinkedHashMapimplementation.This constructor is useful for creating a case-insensitive set with predictable iteration order and default configuration.
-
CaseInsensitiveSet
Constructs aCaseInsensitiveSetcontaining the elements of the specified collection.The backing map is chosen based on the type of the input collection:
- If the input collection is a
ConcurrentNavigableSetNullSafe, the backing map is aConcurrentNavigableMapNullSafe. - If the input collection is a
ConcurrentSkipListSet, the backing map is aConcurrentSkipListMap. - If the input collection is a
ConcurrentSet, the backing map is aConcurrentHashMapNullSafe. - If the input collection is a
SortedSet, the backing map is aTreeMap. - For all other collection types, the backing map is a
LinkedHashMapwith an initial capacity based on the size of the input collection.
- Parameters:
collection- the collection whose elements are to be placed into this set- Throws:
NullPointerException- if the specified collection isnull
- If the input collection is a
-
CaseInsensitiveSet
Constructs aCaseInsensitiveSetcontaining the elements of the specified collection, using the provided map as the backing implementation.This constructor allows full control over the underlying map implementation, enabling custom behavior for the set.
- Parameters:
source- the collection whose elements are to be placed into this setbackingMap- the map to be used as the backing implementation- Throws:
NullPointerException- if the specified collection or map isnull
-
CaseInsensitiveSet
public CaseInsensitiveSet(int initialCapacity) Constructs an emptyCaseInsensitiveSetwith the specified initial capacity.This constructor is useful for creating a set with a predefined capacity to reduce resizing overhead during population.
- Parameters:
initialCapacity- the initial capacity of the backing map- Throws:
IllegalArgumentException- if the specified initial capacity is negative
-
CaseInsensitiveSet
public CaseInsensitiveSet(int initialCapacity, float loadFactor) Constructs an emptyCaseInsensitiveSetwith the specified initial capacity and load factor.This constructor allows fine-grained control over the performance characteristics of the backing map.
- Parameters:
initialCapacity- the initial capacity of the backing maploadFactor- the load factor of the backing map, which determines when resizing occurs- Throws:
IllegalArgumentException- if the specified initial capacity is negative or if the load factor is non-positive
-
-
Method Details
-
hashCode
public int hashCode()For
Stringelements, the hash code computation is case-insensitive, as it relies on the case-insensitive hash codes provided by the underlyingCaseInsensitiveMap.- Specified by:
hashCodein interfaceCollection<E>- Specified by:
hashCodein interfaceSet<E>- Overrides:
hashCodein classAbstractSet<E>
-
equals
For
Stringelements, equality is determined in a case-insensitive manner, ensuring that two sets containing equivalent strings with different cases (e.g., "Hello" and "hello") are considered equal.- Specified by:
equalsin interfaceCollection<E>- Specified by:
equalsin interfaceSet<E>- Overrides:
equalsin classAbstractSet<E>- Parameters:
other- the object to be compared for equality with this set- Returns:
trueif the specified object is equal to this set- See Also:
-
size
public int size()Returns the number of elements in this set. For
Stringelements, the count is determined in a case-insensitive manner, ensuring that equivalent strings with different cases (e.g., "Hello" and "hello") are counted as a single element.- Specified by:
sizein interfaceCollection<E>- Specified by:
sizein interfaceSet<E>- Specified by:
sizein classAbstractCollection<E>- Returns:
- the number of elements in this set
-
isEmpty
public boolean isEmpty()Returns
trueif this set contains no elements. ForStringelements, the check is performed in a case-insensitive manner, ensuring that equivalent strings with different cases are treated as a single element.- Specified by:
isEmptyin interfaceCollection<E>- Specified by:
isEmptyin interfaceSet<E>- Overrides:
isEmptyin classAbstractCollection<E>- Returns:
trueif this set contains no elements,falseotherwise
-
contains
Returns
trueif this set contains the specified element. ForStringelements, the check is performed in a case-insensitive manner, meaning that strings differing only by case (e.g., "Hello" and "hello") are considered equal.- Specified by:
containsin interfaceCollection<E>- Specified by:
containsin interfaceSet<E>- Overrides:
containsin classAbstractCollection<E>- Parameters:
o- the element whose presence in this set is to be tested- Returns:
trueif this set contains the specified element,falseotherwise
-
iterator
Returns an iterator over the elements in this set. For
Stringelements, the iterator preserves the original case of the strings, even though the set performs case-insensitive comparisons.When the backing map is a ConcurrentHashMap, the returned iterator is weakly consistent and will not throw
ConcurrentModificationException. The iterator may reflect updates made during traversal, but is not required to do so. -
toArray
Returns an array containing all the elements in this set. For
Stringelements, the array preserves the original case of the strings, even though the set performs case-insensitive comparisons.- Specified by:
toArrayin interfaceCollection<E>- Specified by:
toArrayin interfaceSet<E>- Overrides:
toArrayin classAbstractCollection<E>- Returns:
- an array containing all the elements in this set
-
toArray
public <T> T[] toArray(T[] a) Returns an array containing all the elements in this set. The runtime type of the returned array is that of the specified array. For
Stringelements, the array preserves the original case of the strings, even though the set performs case-insensitive comparisons.- Specified by:
toArrayin interfaceCollection<E>- Specified by:
toArrayin interfaceSet<E>- Overrides:
toArrayin classAbstractCollection<E>- Parameters:
a- the array into which the elements of the set are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose- Returns:
- an array containing all the elements in this set
- Throws:
ArrayStoreException- if the runtime type of the specified array is not a supertype of the runtime type of every element in this setNullPointerException- if the specified array isnull
-
add
Adds the specified element to this set if it is not already present. For
Stringelements, the addition is case-insensitive, meaning that strings differing only by case (e.g., "Hello" and "hello") are considered equal, and only one instance is added to the set.- Specified by:
addin interfaceCollection<E>- Specified by:
addin interfaceSet<E>- Overrides:
addin classAbstractCollection<E>- Parameters:
e- the element to be added to this set- Returns:
trueif this set did not already contain the specified element
-
remove
Removes the specified element from this set if it is present. For
Stringelements, the removal is case-insensitive, meaning that strings differing only by case (e.g., "Hello" and "hello") are treated as equal, and removing any of them will remove the corresponding entry from the set.- Specified by:
removein interfaceCollection<E>- Specified by:
removein interfaceSet<E>- Overrides:
removein classAbstractCollection<E>- Parameters:
o- the object to be removed from this set, if present- Returns:
trueif this set contained the specified element
-
containsAll
Returns
trueif this set contains all of the elements in the specified collection. ForStringelements, the comparison is case-insensitive, meaning that strings differing only by case (e.g., "Hello" and "hello") are treated as equal.- Specified by:
containsAllin interfaceCollection<E>- Specified by:
containsAllin interfaceSet<E>- Overrides:
containsAllin classAbstractCollection<E>- Parameters:
c- the collection to be checked for containment in this set- Returns:
trueif this set contains all of the elements in the specified collection- Throws:
NullPointerException- if the specified collection isnull
-
addAll
Adds all the elements in the specified collection to this set if they're not already present. For
Stringelements, the addition is case-insensitive, meaning that strings differing only by case (e.g., "Hello" and "hello") are treated as equal, and only one instance is added to the set.- Specified by:
addAllin interfaceCollection<E>- Specified by:
addAllin interfaceSet<E>- Overrides:
addAllin classAbstractCollection<E>- Parameters:
c- the collection containing elements to be added to this set- Returns:
trueif this set changed as a result of the call- Throws:
NullPointerException- if the specified collection isnullor containsnullelements
-
retainAll
Retains only the elements in this set that are contained in the specified collection. For
Stringelements, the comparison is case-insensitive, meaning that strings differing only by case (e.g., "Hello" and "hello") are treated as equal.- Specified by:
retainAllin interfaceCollection<E>- Specified by:
retainAllin interfaceSet<E>- Overrides:
retainAllin classAbstractCollection<E>- Parameters:
c- the collection containing elements to be retained in this set- Returns:
trueif this set changed as a result of the call- Throws:
NullPointerException- if the specified collection isnull
-
removeAll
Removes from this set all of its elements that are contained in the specified collection. For
Stringelements, the removal is case-insensitive, meaning that strings differing only by case (e.g., "Hello" and "hello") are treated as equal, and removing any of them will remove the corresponding entry from the set.- Specified by:
removeAllin interfaceCollection<E>- Specified by:
removeAllin interfaceSet<E>- Overrides:
removeAllin classAbstractSet<E>- Parameters:
c- the collection containing elements to be removed from this set- Returns:
trueif this set changed as a result of the call- Throws:
NullPointerException- if the specified collection isnull
-
clear
public void clear()Removes all elements from this set. After this call, the set will be empty. For
Stringelements, the case-insensitive behavior of the set has no impact on the clearing operation.- Specified by:
clearin interfaceCollection<E>- Specified by:
clearin interfaceSet<E>- Overrides:
clearin classAbstractCollection<E>
-
spliterator
Creates aSpliteratorover the elements in this set.The spliterator reports
Spliterator.DISTINCT. The spliterator's comparator isnullif the set's comparator isnull. Otherwise, the spliterator's comparator is the same as or imposes the same total ordering as the set's comparator.- Specified by:
spliteratorin interfaceCollection<E>- Specified by:
spliteratorin interfaceIterable<E>- Specified by:
spliteratorin interfaceSet<E>- Returns:
- a
Spliteratorover the elements in this set - Since:
- 1.8
-
removeIf
Removes all of the elements of this collection that satisfy the given predicate.Errors or runtime exceptions thrown during iteration or by the predicate are relayed to the caller. For
Stringelements, the removal is case-insensitive.- Specified by:
removeIfin interfaceCollection<E>- Parameters:
filter- a predicate which returnstruefor elements to be removed- Returns:
trueif any elements were removed- Throws:
NullPointerException- if the specified filter is null- Since:
- 1.8
-
forEach
Performs the given action for each element of the set until all elements have been processed or the action throws an exception.Actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller.
- Specified by:
forEachin interfaceIterable<E>- Parameters:
action- The action to be performed for each element- Throws:
NullPointerException- if the specified action is null- Since:
- 1.8
-
elementCount
public long elementCount()Returns an estimate of the number of elements in this set when backed by a ConcurrentHashMap. This method provides better performance and handles large sets (size > Integer.MAX_VALUE).When the backing map is not a ConcurrentHashMap, this method delegates to
size(). The estimate may not reflect recent additions or removals due to concurrent modifications.- Returns:
- the estimated number of elements in this set
- Since:
- 3.6.0
-
forEach
Performs the given action for each element in this set, with operations potentially performed in parallel when the parallelism threshold is met and the set is backed by a ConcurrentHashMap.This method provides high-performance parallel iteration over set elements when using concurrent backing maps. The parallelism threshold determines the minimum set size required to enable parallel processing.
- Parameters:
parallelismThreshold- the threshold for parallel execution (typically use 1 for parallel, Long.MAX_VALUE for sequential)action- the action to be performed for each element- Throws:
NullPointerException- if the specified action is null- Since:
- 3.6.0
-
searchElements
public <U> U searchElements(long parallelismThreshold, Function<? super E, ? extends U> searchFunction) Returns a non-null result from applying the given search function to each element in this set, or null if none are found. The search may be performed in parallel when the parallelism threshold is met and the set is backed by a ConcurrentHashMap.This method provides high-performance parallel search over set elements when using concurrent backing maps. The search terminates early upon finding the first non-null result.
- Type Parameters:
U- the type of the search result- Parameters:
parallelismThreshold- the threshold for parallel execution (typically use 1 for parallel, Long.MAX_VALUE for sequential)searchFunction- the function to apply to each element- Returns:
- a non-null result from applying the search function, or null if none found
- Throws:
NullPointerException- if the specified search function is null- Since:
- 3.6.0
-
reduceElements
public <U> U reduceElements(long parallelismThreshold, Function<? super E, ? extends U> transformer, BiFunction<? super U, ? super U, ? extends U> reducer) Returns the result of accumulating all elements in this set using the given reducer and transformer functions. The reduction may be performed in parallel when the parallelism threshold is met and the set is backed by a ConcurrentHashMap.This method provides high-performance parallel reduction over set elements when using concurrent backing maps. The transformer is applied to each element before reduction.
- Type Parameters:
U- the type of the transformed elements and the result- Parameters:
parallelismThreshold- the threshold for parallel execution (typically use 1 for parallel, Long.MAX_VALUE for sequential)transformer- the function to transform each element before reductionreducer- the function to combine transformed elements- Returns:
- the result of the reduction, or null if the set is empty
- Throws:
NullPointerException- if the specified transformer or reducer is null- Since:
- 3.6.0
-
getBackingMap
Returns the underlying map used to implement this set.This method provides access to the backing
CaseInsensitiveMapimplementation, allowing advanced operations and inspections. The returned map maintains the same case-insensitive semantics as this set.Warning: Modifying the returned map directly may affect this set's state. Use with caution and prefer the set's public methods when possible.
- Returns:
- the backing map implementation
- Since:
- 3.6.0
-
minus
Deprecated.UseremoveAll(Collection)insteadRemoves all elements in the specified collection from this set.This method is deprecated. Use
removeAll(Collection)instead.- Parameters:
removeMe- the collection of elements to remove- Returns:
- this set (for method chaining)
-
minus
Deprecated.Useremove(Object)insteadRemoves the specified element from this set.This method is deprecated. Use
remove(Object)instead.- Parameters:
removeMe- the element to remove- Returns:
- this set (for method chaining)
-
plus
Deprecated.UseaddAll(Collection)insteadAdds all elements in the specified collection to this set.This method is deprecated. Use
addAll(Collection)instead.- Parameters:
right- the collection of elements to add- Returns:
- this set (for method chaining)
-
plus
Deprecated.Useadd(Object)insteadAdds the specified element to this set.This method is deprecated. Use
add(Object)instead.- Parameters:
right- the element to add- Returns:
- this set (for method chaining)
-
toString
Returns a string representation of this set. The string representation consists of a list of the set's elements in their original case, enclosed in square brackets (
"[]"). ForStringelements, the original case is preserved, even though the set performs case-insensitive comparisons.The order of elements in the string representation matches the iteration order of the backing map.
- Overrides:
toStringin classAbstractCollection<E>- Returns:
- a string representation of this set
-
remove(Object)instead