-
Notifications
You must be signed in to change notification settings - Fork 53
io microsphere collection CollectionUtils
Type: Class | Module: microsphere-java-core | Package: io.microsphere.collection
Source:
microsphere-java-core/src/main/java/io/microsphere/collection/CollectionUtils.java
The utilities class for Java Collection
public abstract class CollectionUtils implements UtilsAuthor: Mercy
-
Introduced in:
0.1.10-SNAPSHOT(current) -
Current Project Version:
0.1.10-SNAPSHOT
This component is tested and compatible with the following Java versions:
| Java Version | Status |
|---|---|
| Java 8 | ✅ Compatible |
| Java 11 | ✅ Compatible |
| Java 17 | ✅ Compatible |
| Java 21 | ✅ Compatible |
| Java 25 | ✅ Compatible |
CollectionUtils.isEmpty(null) // returns true
CollectionUtils.isEmpty(Collections.emptyList()) // returns true
CollectionUtils.isEmpty(Arrays.asList(1, 2, 3)) // returns falseCollectionUtils.isNotEmpty(null) // returns false
CollectionUtils.isNotEmpty(Collections.emptyList()) // returns false
CollectionUtils.isNotEmpty(Arrays.asList(1, 2, 3)) // returns true// Convert a non-null collection to iterable
Collection<String> list = Arrays.asList("a", "b", "c");
Iterable<String> iterable = CollectionUtils.toIterable(list);
// Convert a null collection to iterable
Iterable<String> emptyIterable = CollectionUtils.toIterable(null); // returns empty iterable// Convert a non-null iterator to iterable
Iterator<String> iterator = Arrays.asList("a", "b", "c").iterator();
Iterable<String> iterable = CollectionUtils.toIterable(iterator);
// Convert a null iterator to iterable
Iterable<String> emptyIterable = CollectionUtils.toIterable(null); // returns empty iterable// Convert a non-null enumeration to iterator
Enumeration<String> enumeration = Collections.enumeration(Arrays.asList("a", "b", "c"));
Iterator<String> iterator = CollectionUtils.toIterator(enumeration);
// Convert a null enumeration to iterator
Iterator<String> emptyIterator = CollectionUtils.toIterator(null); // returns empty iterator// Convert a non-null enumeration to iterable
Enumeration<String> enumeration = Collections.enumeration(Arrays.asList("a", "b", "c"));
Iterable<String> iterable = CollectionUtils.toIterable(enumeration);
// Convert a null enumeration to iterable
Iterable<String> emptyIterable = CollectionUtils.toIterable(null); // returns empty iterable// Create an iterable with a non-null element
Iterable<String> iterable1 = CollectionUtils.singletonIterable("hello");
// Create an empty iterable from a null element
Iterable<String> iterable2 = CollectionUtils.singletonIterable(null);// Create an iterator with a non-null element
Iterator<String> iterator1 = CollectionUtils.singletonIterator("hello");
// Create an empty iterator from a null element
Iterator<String> iterator2 = CollectionUtils.singletonIterator(null);// Create an enumeration with a non-null element
Enumeration<String> enumeration1 = CollectionUtils.singletonEnumeration("hello");
// Create an empty enumeration from a null element
Enumeration<String> enumeration2 = CollectionUtils.singletonEnumeration(null);// Wrap a valid iterator into an unmodifiable one
Iterator<String> modifiable = Arrays.asList("a", "b", "c").iterator();
Iterator<String> unmodifiable = CollectionUtils.unmodifiableIterator(modifiable);
// Attempting to remove will throw an exception
if (unmodifiable.hasNext()) {
unmodifiable.next();
unmodifiable.remove(); // throws UnsupportedOperationException
}
// Passing null returns an empty unmodifiable iterator
Iterator<String> empty = CollectionUtils.unmodifiableIterator(null);
assert !empty.hasNext();Iterator<String> emptyIterator = CollectionUtils.emptyIterator();
System.out.println(emptyIterator.hasNext()); // prints: falseIterable<String> empty = CollectionUtils.emptyIterable();
System.out.println(empty.iterator().hasNext()); // prints: falseCollectionUtils.size(null) // returns 0
CollectionUtils.size(Collections.emptyList()) // returns 0
CollectionUtils.size(Arrays.asList(1, 2, 3)) // returns 3CollectionUtils.size((Iterable<?>) null) // returns 0
Iterable<String> emptyList = Collections.emptyList();
CollectionUtils.size(emptyList) // returns 0
List<Integer> numbers = Arrays.asList(1, 2, 3);
CollectionUtils.size(numbers) // returns 3
Iterable<String> singleton = CollectionUtils.singletonIterable("hello");
CollectionUtils.size(singleton) // returns 1Collection<String> collection = new ArrayList<>();
int count1 = CollectionUtils.addAll(collection, "a", "b", "c"); // returns 3
int count2 = CollectionUtils.addAll(null, "a", "b"); // returns 0
int count3 = CollectionUtils.addAll(collection, (String[]) null); // returns 0
Collection<String> emptyCollection = Collections.emptyList();
int count4 = CollectionUtils.addAll(emptyCollection, "x"); // returns 0Collection<String> collection = new ArrayList<>();
Iterable<String> values = Arrays.asList("a", "b", "c");
int count1 = CollectionUtils.addAll(collection, values); // returns 3
int count2 = CollectionUtils.addAll(null, values); // returns 0
int count3 = CollectionUtils.addAll(collection, (Iterable<String>) null); // returns 0
Collection<String> emptyCollection = Collections.emptyList();
int count4 = CollectionUtils.addAll(emptyCollection, values); // returns 0Collection<String> list = Arrays.asList("a", "b", "c");
String result1 = CollectionUtils.first(list); // returns "a"
Collection<String> empty = Collections.emptyList();
String result2 = CollectionUtils.first(empty); // returns null
Collection<String> nullCollection = null;
String result3 = CollectionUtils.first(nullCollection); // returns null// Get the first element from a non-empty iterable
Iterable<String> iterable1 = Arrays.asList("apple", "banana");
String result1 = CollectionUtils.first(iterable1); // returns "apple"
// Get the first element from an empty iterable
Iterable<String> iterable2 = Collections.emptyList();
String result2 = CollectionUtils.first(iterable2); // returns null
// Get the first element from a null iterable
String result3 = CollectionUtils.first(null); // returns null// Get the first element from a non-empty iterator
Iterator<String> iterator1 = Arrays.asList("apple", "banana").iterator();
String result1 = CollectionUtils.first(iterator1); // returns "apple"
// Get the first element from an empty iterator
Iterator<String> iterator2 = Collections.emptyIterator();
String result2 = CollectionUtils.first(iterator2); // returns null
// Get the first element from a null iterator
String result3 = CollectionUtils.first(null); // returns nullQueue<String> emptyQueue = CollectionUtils.emptyQueue();
System.out.println(emptyQueue.isEmpty()); // true
System.out.println(emptyQueue.size()); // 0
try {
emptyQueue.add("test");
} catch (UnsupportedOperationException e) {
System.out.println("Modification not allowed"); // This block will execute
}Add the following dependency to your pom.xml:
<dependency>
<groupId>io.github.microsphere-projects</groupId>
<artifactId>microsphere-java-core</artifactId>
<version>${microsphere-java.version}</version>
</dependency>Tip: Use the BOM (
microsphere-java-dependencies) for consistent version management. See the Getting Started guide.
import io.microsphere.collection.CollectionUtils;| Method | Description |
|---|---|
isEmpty |
Checks if the provided collection is null or empty. |
isNotEmpty |
Checks if the provided collection is not null and not empty. |
toIterable |
Converts a nullable Collection into an Iterable. |
toIterable |
Converts a nullable Iterator into an Iterable. |
toIterator |
Converts a nullable Enumeration into an Iterator. |
toIterable |
Converts a nullable Enumeration into an Iterable. |
singletonIterable |
Creates a singleton Iterable that contains only the specified element. |
singletonIterator |
Creates a singleton read-only Iterator that contains only the specified element. |
singletonEnumeration |
Creates a singleton read-only Enumeration that contains only the specified element. |
unmodifiableIterator |
Returns an unmodifiable (read-only) view of the given iterator. |
emptyIterator |
Returns an empty iterator that contains no elements. |
emptyIterable |
Returns an empty, immutable Iterable that contains no elements. |
size |
Returns the size of the specified Collection. |
size |
Returns the size of the specified Iterable. |
addAll |
Adds all the elements in the specified array to the given collection. |
addAll |
Adds all the elements in the specified Iterable to the given collection. |
first |
Retrieves the first element from the given collection. |
first |
Retrieves the first element from the given Iterable. |
first |
Retrieves the first element from the given Iterator. |
emptyQueue |
Returns an empty, immutable Queue that throws UnsupportedOperationException
|
public static boolean isEmpty(@Nullable Collection<?> collection)Checks if the provided collection is null or empty.
public static boolean isNotEmpty(@Nullable Collection<?> collection)Checks if the provided collection is not null and not empty.
public static <E> Iterable<E> toIterable(@Nullable Collection<E> collection)Converts a nullable Collection into an Iterable.
If the provided collection is null, it returns an empty iterable.
public static <E> Iterable<E> toIterable(@Nullable Iterator<E> iterator)Converts a nullable Iterator into an Iterable.
If the provided iterator is null, it returns an empty iterable.
public static <E> Iterator<E> toIterator(@Nullable Enumeration<E> enumeration)Converts a nullable Enumeration into an Iterator.
If the provided enumeration is null, it returns an empty iterator.
public static <E> Iterable<E> toIterable(@Nullable Enumeration<E> enumeration)Converts a nullable Enumeration into an Iterable.
If the provided enumeration is null, it returns an empty iterable.
public static <E> Iterable<E> singletonIterable(@Nullable E element)Creates a singleton Iterable that contains only the specified element.
If the provided element is null, returns an empty iterable.
public static <E> Iterator<E> singletonIterator(@Nullable E element)Creates a singleton read-only Iterator that contains only the specified element.
If the provided element is null, returns an iterator with no elements.
The returned iterator is read-only and cannot be used to remove elements.
public static <E> Enumeration<E> singletonEnumeration(@Nullable E element)Creates a singleton read-only Enumeration that contains only the specified element.
If the provided element is null, returns an enumeration with no elements.
The returned enumeration is read-only and cannot be used to remove elements.
public static <E> Iterator<E> unmodifiableIterator(@Nullable Iterator<E> iterator)Returns an unmodifiable (read-only) view of the given iterator.
Attempts to modify the underlying data structure via the returned iterator will result in
an UnsupportedOperationException.
If the provided iterator is null, this method returns an empty unmodifiable iterator.
public static <E> Iterator<E> emptyIterator()Returns an empty iterator that contains no elements.
Any call to Iterator#hasNext() will return false, and any call to
Iterator#next() will throw a java.util.NoSuchElementException.
public static <E> Iterable<E> emptyIterable()Returns an empty, immutable Iterable that contains no elements.
Any attempt to iterate over the returned iterable will result in:
-
Iterator#hasNext()always returnsfalse -
Iterator#next()throws ajava.util.NoSuchElementException
public static int size(@Nullable Collection<?> collection)Returns the size of the specified Collection.
If the provided collection is null, this method returns 0.
public static int size(@Nullable Iterable<?> iterable)Returns the size of the specified Iterable.
If the provided iterable is null, this method returns 0.
public static <T> int addAll(@Nullable Collection<T> collection, T... newValues)Adds all the elements in the specified array to the given collection.
If the provided collection is null or empty, no elements are added, and 0 is returned. If the array is null or has no elements, 0 is also returned.
public static <T> int addAll(@Nullable Collection<T> collection, @Nullable Iterable<T> newValues)Adds all the elements in the specified Iterable to the given collection.
If the provided collection is null or empty, no elements are added, and 0 is returned. If the iterable is null or has no elements, 0 is also returned.
public static <T> T first(@Nullable Collection<T> values)Retrieves the first element from the given collection.
If the collection is null or empty, this method returns null.
If the collection is an instance of a list, it delegates to ListUtils#first(List).
Otherwise, it retrieves the first element using the iterator obtained from the collection.
`Collection list = Arrays.asList("a", "b", "c");
String result1 = CollectionUtils.first(list); // returns "a"
Collection empty = Collections.emptyList();
String result2 = CollectionUtils.first(empty); // returns null
Collection nullCollection = null;
String result3 = CollectionUtils.first(nullCollection); // returns null
`
public static <T> T first(@Nullable Iterable<T> values)Retrieves the first element from the given Iterable.
If the iterable is null or has no elements, this method returns null.
public static <T> T first(@Nullable Iterator<T> values)Retrieves the first element from the given Iterator.
If the iterator is null or has no elements, this method returns null.
public static <T> Queue<T> emptyQueue()Returns an empty, immutable Queue that throws UnsupportedOperationException
for all modification operations.
This method returns a singleton instance of an empty queue. Any attempt to modify the returned queue
will result in an UnsupportedOperationException. It is useful as a placeholder or default value
where an empty queue is needed without creating a new instance every time.
`Queue emptyQueue = CollectionUtils.emptyQueue();
System.out.println(emptyQueue.isEmpty()); // true
System.out.println(emptyQueue.size()); // 0
try {
emptyQueue.add("test");
` catch (UnsupportedOperationException e) {
System.out.println("Modification not allowed"); // This block will execute
}
}
Collections
This documentation was auto-generated from the source code of microsphere-java.
java-annotations
java-core
- ACLLoggerFactory
- AbstractArtifactResourceResolver
- AbstractConverter
- AbstractDeque
- AbstractEventDispatcher
- AbstractLogger
- AbstractURLClassPathHandle
- AccessibleObjectUtils
- AdditionalMetadataResourceConfigurationPropertyLoader
- AnnotationUtils
- ArchiveFileArtifactResourceResolver
- ArrayEnumeration
- ArrayStack
- ArrayUtils
- Artifact
- ArtifactDetector
- ArtifactResourceResolver
- Assert
- BannedArtifactClassLoadingExecutor
- BaseUtils
- BeanMetadata
- BeanProperty
- BeanUtils
- ByteArrayToObjectConverter
- CharSequenceComparator
- CharSequenceUtils
- CharsetUtils
- ClassDataRepository
- ClassDefinition
- ClassFileJarEntryFilter
- ClassFilter
- ClassLoaderUtils
- ClassPathResourceConfigurationPropertyLoader
- ClassPathUtils
- ClassUtils
- ClassicProcessIdResolver
- ClassicURLClassPathHandle
- CollectionUtils
- Compatible
- CompositeSubProtocolURLConnectionFactory
- CompositeURLStreamHandlerFactory
- ConditionalEventListener
- ConfigurationProperty
- ConfigurationPropertyGenerator
- ConfigurationPropertyLoader
- ConfigurationPropertyReader
- Configurer
- ConsoleURLConnection
- Constants
- ConstructorDefinition
- ConstructorUtils
- Converter
- Converters
- CustomizedThreadFactory
- DefaultConfigurationPropertyGenerator
- DefaultConfigurationPropertyReader
- DefaultDeserializer
- DefaultEntry
- DefaultSerializer
- DelegatingBlockingQueue
- DelegatingDeque
- DelegatingIterator
- DelegatingQueue
- DelegatingScheduledExecutorService
- DelegatingURLConnection
- DelegatingURLStreamHandlerFactory
- DelegatingWrapper
- Deprecation
- Deserializer
- Deserializers
- DirectEventDispatcher
- DirectoryFileFilter
- EmptyDeque
- EmptyIterable
- EmptyIterator
- EnumerationIteratorAdapter
- EnumerationUtils
- Event
- EventDispatcher
- EventListener
- ExceptionUtils
- ExecutableDefinition
- ExecutableUtils
- ExecutorUtils
- ExtendableProtocolURLStreamHandler
- FastByteArrayInputStream
- FastByteArrayOutputStream
- FieldDefinition
- FieldUtils
- FileChangedEvent
- FileChangedListener
- FileConstants
- FileExtensionFilter
- FileUtils
- FileWatchService
- Filter
- FilterOperator
- FilterUtils
- FormatUtils
- Functional
- GenericEvent
- GenericEventListener
- Handler
- Handler
- HierarchicalClassComparator
- IOFileFilter
- IOUtils
- ImmutableEntry
- IterableAdapter
- IterableUtils
- Iterators
- JDKLoggerFactory
- JSON
- JSONArray
- JSONException
- JSONObject
- JSONStringer
- JSONTokener
- JSONUtils
- JarEntryFilter
- JarUtils
- JavaType
- JmxUtils
- ListUtils
- Listenable
- Lists
- Logger
- LoggerFactory
- LoggingFileChangedListener
- MBeanAttribute
- MBeanAttributeInfoBuilder
- MBeanConstructorInfoBuilder
- MBeanDescribableBuilder
- MBeanExecutableInfoBuilder
- MBeanFeatureInfoBuilder
- MBeanInfoBuilder
- MBeanNotificationInfoBuilder
- MBeanOperationInfoBuilder
- MBeanParameterInfoBuilder
- ManagementUtils
- ManifestArtifactResourceResolver
- MapToPropertiesConverter
- MapUtils
- Maps
- MavenArtifact
- MavenArtifactResourceResolver
- MemberDefinition
- MemberUtils
- MetadataResourceConfigurationPropertyLoader
- MethodDefinition
- MethodHandleUtils
- MethodHandlesLookupUtils
- MethodUtils
- ModernProcessIdResolver
- ModernURLClassPathHandle
- Modifier
- MultiValueConverter
- MultipleType
- MutableInteger
- MutableURLStreamHandlerFactory
- NameFileFilter
- NoOpLogger
- NoOpLoggerFactory
- NoOpURLClassPathHandle
- NumberToByteConverter
- NumberToCharacterConverter
- NumberToDoubleConverter
- NumberToFloatConverter
- NumberToIntegerConverter
- NumberToLongConverter
- NumberToShortConverter
- NumberUtils
- ObjectToBooleanConverter
- ObjectToByteArrayConverter
- ObjectToByteConverter
- ObjectToCharacterConverter
- ObjectToDoubleConverter
- ObjectToFloatConverter
- ObjectToIntegerConverter
- ObjectToLongConverter
- ObjectToOptionalConverter
- ObjectToShortConverter
- ObjectToStringConverter
- PackageNameClassFilter
- PackageNameClassNameFilter
- ParallelEventDispatcher
- ParameterizedTypeImpl
- PathConstants
- Predicates
- Prioritized
- PriorityComparator
- ProcessExecutor
- ProcessIdResolver
- ProcessManager
- PropertiesToStringConverter
- PropertiesUtils
- PropertyConstants
- PropertyResourceBundleControl
- PropertyResourceBundleUtils
- ProtocolConstants
- ProxyUtils
- QueueUtils
- ReadOnlyIterator
- ReflectionUtils
- ReflectiveConfigurationPropertyGenerator
- ReflectiveDefinition
- ResourceConstants
- ReversedDeque
- Scanner
- SecurityUtils
- SeparatorConstants
- Serializer
- Serializers
- ServiceLoaderURLStreamHandlerFactory
- ServiceLoaderUtils
- ServiceLoadingURLClassPathHandle
- SetUtils
- Sets
- Sfl4jLoggerFactory
- ShutdownHookCallbacksThread
- ShutdownHookUtils
- SimpleClassScanner
- SimpleFileScanner
- SimpleJarEntryScanner
- SingletonDeque
- SingletonEnumeration
- SingletonIterator
- StackTraceUtils
- StandardFileWatchService
- StandardURLStreamHandlerFactory
- StopWatch
- StreamArtifactResourceResolver
- Streams
- StringBuilderWriter
- StringConverter
- StringDeserializer
- StringSerializer
- StringToArrayConverter
- StringToBlockingDequeConverter
- StringToBlockingQueueConverter
- StringToBooleanConverter
- StringToByteConverter
- StringToCharArrayConverter
- StringToCharacterConverter
- StringToClassConverter
- StringToCollectionConverter
- StringToDequeConverter
- StringToDoubleConverter
- StringToDurationConverter
- StringToFloatConverter
- StringToInputStreamConverter
- StringToIntegerConverter
- StringToIterableConverter
- StringToListConverter
- StringToLongConverter
- StringToMultiValueConverter
- StringToNavigableSetConverter
- StringToQueueConverter
- StringToSetConverter
- StringToShortConverter
- StringToSortedSetConverter
- StringToStringConverter
- StringToTransferQueueConverter
- StringUtils
- SubProtocolURLConnectionFactory
- SymbolConstants
- SystemUtils
- ThrowableAction
- ThrowableBiConsumer
- ThrowableBiFunction
- ThrowableConsumer
- ThrowableFunction
- ThrowableSupplier
- ThrowableUtils
- TrueClassFilter
- TrueFileFilter
- TypeArgument
- TypeFinder
- TypeUtils
- URLClassPathHandle
- URLUtils
- UnmodifiableDeque
- UnmodifiableIterator
- UnmodifiableQueue
- Utils
- ValueHolder
- Version
- VersionUtils
- VirtualMachineProcessIdResolver
- Wrapper
- WrapperProcessor
jdk-tools
lang-model
- AnnotatedElementJSONElementVisitor
- AnnotationUtils
- ClassUtils
- ConstructorUtils
- ElementUtils
- ExecutableElementComparator
- FieldUtils
- JSONAnnotationValueVisitor
- JSONElementVisitor
- LoggerUtils
- MemberUtils
- MessagerUtils
- MethodUtils
- ResolvableAnnotationValueVisitor
- StringAnnotationValue
- TypeUtils
annotation-processor
- ConfigurationPropertyAnnotationProcessor
- ConfigurationPropertyJSONElementVisitor
- FilerProcessor
- ResourceProcessor
java-test
- AbstractAnnotationProcessingTest
- Ancestor
- AnnotationProcessingTestProcessor
- ArrayTypeModel
- CollectionTypeModel
- Color
- CompilerInvocationInterceptor
- ConfigurationPropertyModel
- DefaultTestService
- GenericTestService
- MapTypeModel
- Model
- Parent
- PrimitiveTypeModel
- SimpleTypeModel
- StringArrayList
- TestAnnotation
- TestService
- TestServiceImpl