Class CaseInsensitiveSet<E>
- Type Parameters:
E- the type of elements maintained by this set
- All Implemented Interfaces:
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().
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.
Deprecated Methods
The following methods are deprecated and retained for backward compatibility:
plus(): UseaddAll(Collection)instead.minus(): UseremoveAll(Collection)instead.
Additional Notes
- String comparisons are case-insensitive but preserve original case for iteration and output.
- Thread safety depends on the thread safety of the chosen backing map.
- Set operations like
contains(),add(), andremove()rely on the behavior of the underlyingCaseInsensitiveMap.
- 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.Returns the underlying map used to implement this set.inthashCode()booleanisEmpty()iterator()Deprecated.Deprecated.Deprecated.Deprecated.<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) 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()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, removeIf, stream, toArrayMethods inherited from interface java.util.Set
spliterator
-
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. -
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. -
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. -
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. -
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. -
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. -
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>- 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. -
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. -
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>- 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>- 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>- 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>- 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. -
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. -
minus
Deprecated. -
plus
Deprecated. -
plus
Deprecated. -
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.
-