You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by gg...@apache.org on 2024/01/20 15:46:09 UTC
(commons-collections) 02/04: Sort members
This is an automated email from the ASF dual-hosted git repository.
ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-collections.git
commit 01bd494f071e4389f2e078fc6f08ba0ea8f67002
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Sat Jan 20 10:18:07 2024 -0500
Sort members
---
.../apache/commons/collections4/ArrayUtils.java | 44 +-
.../java/org/apache/commons/collections4/Bag.java | 108 +-
.../org/apache/commons/collections4/BagUtils.java | 186 +-
.../org/apache/commons/collections4/BidiMap.java | 72 +-
.../apache/commons/collections4/ClosureUtils.java | 242 +-
.../commons/collections4/CollectionUtils.java | 2860 ++++++++--------
.../commons/collections4/ComparatorUtils.java | 162 +-
.../commons/collections4/EnumerationUtils.java | 14 +-
.../apache/commons/collections4/FactoryUtils.java | 92 +-
.../commons/collections4/FluentIterable.java | 326 +-
.../commons/collections4/FunctorException.java | 14 +-
.../java/org/apache/commons/collections4/Get.java | 16 +-
.../apache/commons/collections4/IterableUtils.java | 1148 +++----
.../apache/commons/collections4/IteratorUtils.java | 1504 ++++-----
.../apache/commons/collections4/MapIterator.java | 34 +-
.../org/apache/commons/collections4/MultiMap.java | 76 +-
.../apache/commons/collections4/MultiMapUtils.java | 116 +-
.../org/apache/commons/collections4/MultiSet.java | 254 +-
.../apache/commons/collections4/MultiSetUtils.java | 60 +-
.../commons/collections4/MultiValuedMap.java | 192 +-
.../apache/commons/collections4/OrderedMap.java | 22 +-
.../commons/collections4/PredicateUtils.java | 422 +--
.../apache/commons/collections4/QueueUtils.java | 74 +-
.../apache/commons/collections4/SplitMapUtils.java | 32 +-
.../commons/collections4/TransformerUtils.java | 438 +--
.../org/apache/commons/collections4/TrieUtils.java | 10 +-
.../collections4/bag/AbstractBagDecorator.java | 14 +-
.../commons/collections4/bag/AbstractMapBag.java | 512 +--
.../bag/AbstractSortedBagDecorator.java | 10 +-
.../commons/collections4/bag/CollectionBag.java | 94 +-
.../collections4/bag/CollectionSortedBag.java | 70 +-
.../apache/commons/collections4/bag/HashBag.java | 22 +-
.../commons/collections4/bag/PredicatedBag.java | 20 +-
.../collections4/bag/PredicatedSortedBag.java | 10 +-
.../commons/collections4/bag/SynchronizedBag.java | 70 +-
.../collections4/bag/SynchronizedSortedBag.java | 40 +-
.../commons/collections4/bag/TransformedBag.java | 58 +-
.../collections4/bag/TransformedSortedBag.java | 56 +-
.../apache/commons/collections4/bag/TreeBag.java | 58 +-
.../commons/collections4/bag/UnmodifiableBag.java | 72 +-
.../collections4/bag/UnmodifiableSortedBag.java | 72 +-
.../bidimap/AbstractBidiMapDecorator.java | 16 +-
.../collections4/bidimap/AbstractDualBidiMap.java | 1014 +++---
.../bidimap/AbstractOrderedBidiMapDecorator.java | 18 +-
.../bidimap/AbstractSortedBidiMapDecorator.java | 26 +-
.../collections4/bidimap/DualHashBidiMap.java | 12 +-
.../bidimap/DualLinkedHashBidiMap.java | 12 +-
.../collections4/bidimap/DualTreeBidiMap.java | 454 +--
.../commons/collections4/bidimap/TreeBidiMap.java | 3410 +++++++++----------
.../collections4/bidimap/UnmodifiableBidiMap.java | 56 +-
.../bidimap/UnmodifiableOrderedBidiMap.java | 72 +-
.../bidimap/UnmodifiableSortedBidiMap.java | 66 +-
.../bloomfilter/ArrayCountingBloomFilter.java | 210 +-
.../commons/collections4/bloomfilter/BitMap.java | 88 +-
.../collections4/bloomfilter/BitMapProducer.java | 132 +-
.../collections4/bloomfilter/BloomFilter.java | 300 +-
.../bloomfilter/BloomFilterProducer.java | 142 +-
.../collections4/bloomfilter/CellProducer.java | 132 +-
.../bloomfilter/CountingBloomFilter.java | 188 +-
.../bloomfilter/CountingLongPredicate.java | 10 +-
.../bloomfilter/CountingPredicate.java | 10 +-
.../bloomfilter/EnhancedDoubleHasher.java | 64 +-
.../collections4/bloomfilter/IndexFilter.java | 104 +-
.../collections4/bloomfilter/IndexProducer.java | 80 +-
.../collections4/bloomfilter/IndexUtils.java | 6 +-
.../collections4/bloomfilter/LayerManager.java | 314 +-
.../bloomfilter/LayeredBloomFilter.java | 326 +-
.../collections4/bloomfilter/SetOperations.java | 74 +-
.../commons/collections4/bloomfilter/Shape.java | 508 +--
.../bloomfilter/SimpleBloomFilter.java | 122 +-
.../bloomfilter/SparseBloomFilter.java | 136 +-
.../bloomfilter/WrappedBloomFilter.java | 76 +-
.../collection/AbstractCollectionDecorator.java | 78 +-
.../collection/CompositeCollection.java | 486 +--
.../collections4/collection/IndexedCollection.java | 118 +-
.../collection/PredicatedCollection.java | 352 +-
.../collection/SynchronizedCollection.java | 78 +-
.../collection/TransformedCollection.java | 80 +-
.../collection/UnmodifiableBoundedCollection.java | 42 +-
.../collection/UnmodifiableCollection.java | 20 +-
.../comparators/BooleanComparator.java | 54 +-
.../comparators/ComparableComparator.java | 24 +-
.../collections4/comparators/ComparatorChain.java | 198 +-
.../comparators/FixedOrderComparator.java | 146 +-
.../collections4/comparators/NullComparator.java | 54 +-
.../comparators/ReverseComparator.java | 24 +-
.../comparators/TransformingComparator.java | 28 +-
.../collections4/functors/AllPredicate.java | 34 +-
.../collections4/functors/AndPredicate.java | 10 +-
.../collections4/functors/AnyPredicate.java | 36 +-
.../collections4/functors/ChainedClosure.java | 6 +-
.../collections4/functors/ChainedTransformer.java | 60 +-
.../collections4/functors/ClosureTransformer.java | 26 +-
.../collections4/functors/ComparatorPredicate.java | 22 +-
.../collections4/functors/ConstantFactory.java | 6 +-
.../collections4/functors/ConstantTransformer.java | 68 +-
.../collections4/functors/EqualPredicate.java | 12 +-
.../functors/ExceptionTransformer.java | 8 +-
.../collections4/functors/FactoryTransformer.java | 26 +-
.../commons/collections4/functors/ForClosure.java | 10 +-
.../collections4/functors/FunctorUtils.java | 152 +-
.../collections4/functors/IdentityPredicate.java | 6 +-
.../commons/collections4/functors/IfClosure.java | 36 +-
.../collections4/functors/IfTransformer.java | 42 +-
.../collections4/functors/InstanceofPredicate.java | 6 +-
.../collections4/functors/InstantiateFactory.java | 40 +-
.../functors/InstantiateTransformer.java | 12 +-
.../collections4/functors/InvokerTransformer.java | 16 +-
.../collections4/functors/MapTransformer.java | 26 +-
.../collections4/functors/NOPTransformer.java | 8 +-
.../collections4/functors/NonePredicate.java | 24 +-
.../collections4/functors/NotPredicate.java | 6 +-
.../functors/NullIsExceptionPredicate.java | 6 +-
.../functors/NullIsFalsePredicate.java | 6 +-
.../collections4/functors/NullIsTruePredicate.java | 6 +-
.../collections4/functors/OnePredicate.java | 28 +-
.../commons/collections4/functors/OrPredicate.java | 10 +-
.../functors/PredicateTransformer.java | 26 +-
.../collections4/functors/PrototypeFactory.java | 124 +-
.../functors/StringValueTransformer.java | 8 +-
.../collections4/functors/SwitchClosure.java | 88 +-
.../collections4/functors/SwitchTransformer.java | 106 +-
.../functors/TransformedPredicate.java | 12 +-
.../collections4/functors/TransformerClosure.java | 6 +-
.../functors/TransformerPredicate.java | 6 +-
.../collections4/functors/UniquePredicate.java | 6 +-
.../collections4/functors/WhileClosure.java | 30 +-
.../iterators/AbstractEmptyIterator.java | 26 +-
.../iterators/AbstractListIteratorDecorator.java | 24 +-
.../iterators/AbstractMapIteratorDecorator.java | 24 +-
.../AbstractOrderedMapIteratorDecorator.java | 32 +-
.../collections4/iterators/ArrayIterator.java | 60 +-
.../collections4/iterators/ArrayListIterator.java | 64 +-
.../collections4/iterators/BoundedIterator.java | 22 +-
.../collections4/iterators/CollatingIterator.java | 266 +-
.../collections4/iterators/EmptyIterator.java | 16 +-
.../collections4/iterators/EmptyListIterator.java | 12 +-
.../iterators/EntrySetMapIterator.java | 70 +-
.../iterators/EnumerationIterator.java | 20 +-
.../collections4/iterators/FilterIterator.java | 58 +-
.../collections4/iterators/FilterListIterator.java | 70 +-
.../collections4/iterators/IteratorChain.java | 152 +-
.../iterators/IteratorEnumeration.java | 18 +-
.../collections4/iterators/LazyIteratorChain.java | 72 +-
.../iterators/ListIteratorWrapper.java | 36 +-
.../iterators/LoopingListIterator.java | 80 +-
.../iterators/ObjectArrayIterator.java | 54 +-
.../iterators/ObjectArrayListIterator.java | 58 +-
.../iterators/ObjectGraphIterator.java | 46 +-
.../collections4/iterators/PeekingIterator.java | 78 +-
.../collections4/iterators/PushbackIterator.java | 32 +-
.../iterators/ReverseListIterator.java | 76 +-
.../iterators/SingletonListIterator.java | 76 +-
.../collections4/iterators/TransformIterator.java | 36 +-
.../iterators/UnmodifiableIterator.java | 6 +-
.../iterators/UnmodifiableListIterator.java | 50 +-
.../iterators/UnmodifiableMapIterator.java | 30 +-
.../iterators/UnmodifiableOrderedMapIterator.java | 36 +-
.../collections4/iterators/ZippingIterator.java | 34 +-
.../collections4/keyvalue/AbstractKeyValue.java | 12 +-
.../collections4/keyvalue/AbstractMapEntry.java | 28 +-
.../keyvalue/AbstractMapEntryDecorator.java | 34 +-
.../collections4/keyvalue/DefaultKeyValue.java | 76 +-
.../collections4/keyvalue/TiedMapEntry.java | 70 +-
.../collections4/list/AbstractLinkedList.java | 1596 ++++-----
.../collections4/list/AbstractListDecorator.java | 28 +-
.../list/AbstractSerializableListDecorator.java | 22 +-
.../collections4/list/CursorableLinkedList.java | 754 ++---
.../commons/collections4/list/FixedSizeList.java | 72 +-
.../apache/commons/collections4/list/LazyList.java | 32 +-
.../collections4/list/NodeCachingLinkedList.java | 134 +-
.../commons/collections4/list/PredicatedList.java | 100 +-
.../commons/collections4/list/SetUniqueList.java | 336 +-
.../commons/collections4/list/TransformedList.java | 142 +-
.../apache/commons/collections4/list/TreeList.java | 964 +++---
.../collections4/list/UnmodifiableList.java | 40 +-
.../collections4/map/AbstractHashedMap.java | 1828 +++++-----
.../map/AbstractInputCheckedMapDecorator.java | 114 +-
.../collections4/map/AbstractLinkedMap.java | 726 ++--
.../collections4/map/AbstractMapDecorator.java | 52 +-
.../map/AbstractOrderedMapDecorator.java | 10 +-
.../collections4/map/AbstractReferenceMap.java | 1596 ++++-----
.../map/AbstractSortedMapDecorator.java | 132 +-
.../collections4/map/CaseInsensitiveMap.java | 34 +-
.../commons/collections4/map/CompositeMap.java | 270 +-
.../commons/collections4/map/DefaultedMap.java | 94 +-
.../map/EntrySetToMapIteratorAdapter.java | 40 +-
.../commons/collections4/map/FixedSizeMap.java | 92 +-
.../collections4/map/FixedSizeSortedMap.java | 96 +-
.../apache/commons/collections4/map/Flat3Map.java | 1820 +++++-----
.../apache/commons/collections4/map/HashedMap.java | 22 +-
.../apache/commons/collections4/map/LRUMap.java | 380 +--
.../apache/commons/collections4/map/LazyMap.java | 48 +-
.../commons/collections4/map/LazySortedMap.java | 26 +-
.../apache/commons/collections4/map/LinkedMap.java | 284 +-
.../commons/collections4/map/ListOrderedMap.java | 1108 +++----
.../commons/collections4/map/MultiKeyMap.java | 690 ++--
.../commons/collections4/map/MultiValueMap.java | 562 ++--
.../collections4/map/PassiveExpiringMap.java | 42 +-
.../commons/collections4/map/PredicatedMap.java | 94 +-
.../collections4/map/PredicatedSortedMap.java | 26 +-
.../collections4/map/ReferenceIdentityMap.java | 22 +-
.../commons/collections4/map/ReferenceMap.java | 22 +-
.../commons/collections4/map/SingletonMap.java | 564 ++--
.../commons/collections4/map/StaticBucketMap.java | 842 ++---
.../commons/collections4/map/TransformedMap.java | 138 +-
.../collections4/map/TransformedSortedMap.java | 68 +-
.../collections4/map/UnmodifiableEntrySet.java | 88 +-
.../commons/collections4/map/UnmodifiableMap.java | 82 +-
.../collections4/map/UnmodifiableOrderedMap.java | 78 +-
.../collections4/map/UnmodifiableSortedMap.java | 92 +-
.../multimap/AbstractListValuedMap.java | 286 +-
.../multimap/AbstractMultiValuedMap.java | 1244 +++----
.../multimap/AbstractMultiValuedMapDecorator.java | 92 +-
.../multimap/AbstractSetValuedMap.java | 74 +-
.../multimap/ArrayListValuedHashMap.java | 20 +-
.../multimap/HashSetValuedHashMap.java | 18 +-
.../multimap/TransformedMultiValuedMap.java | 112 +-
.../multimap/UnmodifiableMultiValuedMap.java | 42 +-
.../collections4/multiset/AbstractMapMultiSet.java | 502 +--
.../collections4/multiset/AbstractMultiSet.java | 530 +--
.../multiset/AbstractMultiSetDecorator.java | 30 +-
.../collections4/multiset/HashMultiSet.java | 22 +-
.../collections4/multiset/PredicatedMultiSet.java | 30 +-
.../multiset/SynchronizedMultiSet.java | 72 +-
.../multiset/UnmodifiableMultiSet.java | 82 +-
.../collections4/queue/AbstractQueueDecorator.java | 12 +-
.../collections4/queue/CircularFifoQueue.java | 364 +-
.../collections4/queue/PredicatedQueue.java | 14 +-
.../collections4/queue/TransformedQueue.java | 50 +-
.../collections4/queue/UnmodifiableQueue.java | 76 +-
.../collections4/sequence/CommandVisitor.java | 14 +-
.../commons/collections4/sequence/EditCommand.java | 18 +-
.../commons/collections4/sequence/EditScript.java | 42 +-
.../collections4/sequence/ReplacementsFinder.java | 20 +-
.../collections4/sequence/SequencesComparator.java | 232 +-
.../set/AbstractNavigableSetDecorator.java | 38 +-
.../set/AbstractSerializableSetDecorator.java | 22 +-
.../set/AbstractSortedSetDecorator.java | 26 +-
.../commons/collections4/set/CompositeSet.java | 564 ++--
.../commons/collections4/set/ListOrderedSet.java | 354 +-
.../commons/collections4/set/MapBackedSet.java | 78 +-
.../collections4/set/PredicatedNavigableSet.java | 40 +-
.../collections4/set/PredicatedSortedSet.java | 20 +-
.../collections4/set/TransformedNavigableSet.java | 76 +-
.../commons/collections4/set/TransformedSet.java | 38 +-
.../collections4/set/TransformedSortedSet.java | 64 +-
.../collections4/set/UnmodifiableNavigableSet.java | 102 +-
.../commons/collections4/set/UnmodifiableSet.java | 20 +-
.../collections4/set/UnmodifiableSortedSet.java | 56 +-
.../splitmap/AbstractIterableGetMapDecorator.java | 64 +-
.../collections4/splitmap/TransformedSplitMap.java | 82 +-
.../collections4/trie/AbstractBitwiseTrie.java | 232 +-
.../collections4/trie/AbstractPatriciaTrie.java | 3500 ++++++++++----------
.../commons/collections4/trie/KeyAnalyzer.java | 82 +-
.../collections4/trie/UnmodifiableTrie.java | 98 +-
.../trie/analyzer/StringKeyAnalyzer.java | 20 +-
.../collections4/AbstractLinkedListTest.java | 38 +-
.../commons/collections4/AbstractObjectTest.java | 306 +-
.../commons/collections4/ArrayStackTest.java | 10 +-
.../apache/commons/collections4/BagUtilsTest.java | 76 +-
.../org/apache/commons/collections4/BulkTest.java | 18 +-
.../commons/collections4/ClosureUtilsTest.java | 172 +-
.../commons/collections4/CollectionUtilsTest.java | 1708 +++++-----
.../commons/collections4/ComparatorUtilsTest.java | 16 +-
.../commons/collections4/EnumerationUtilsTest.java | 36 +-
.../commons/collections4/FactoryUtilsTest.java | 192 +-
.../commons/collections4/FluentIterableTest.java | 284 +-
.../commons/collections4/GuavaTestlibTest.java | 48 +-
.../commons/collections4/IterableUtilsTest.java | 224 +-
.../apache/commons/collections4/ListUtilsTest.java | 28 +-
.../commons/collections4/MapPerformance.java | 142 +-
.../apache/commons/collections4/MapUtilsTest.java | 1640 ++++-----
.../apache/commons/collections4/MockTestCase.java | 8 +-
.../commons/collections4/MultiMapUtilsTest.java | 86 +-
.../commons/collections4/MultiSetUtilsTest.java | 38 +-
.../commons/collections4/PredicateUtilsTest.java | 444 +--
.../commons/collections4/QueueUtilsTest.java | 40 +-
.../apache/commons/collections4/SetUtilsTest.java | 112 +-
.../commons/collections4/SplitMapUtilsTest.java | 44 +-
.../org/apache/commons/collections4/TestUtils.java | 28 +-
.../commons/collections4/TransformerUtilsTest.java | 328 +-
.../commons/collections4/bag/AbstractBagTest.java | 538 +--
.../collections4/bag/AbstractSortedBagTest.java | 120 +-
.../collections4/bag/CollectionBagTest.java | 18 +-
.../collections4/bag/CollectionSortedBagTest.java | 68 +-
.../commons/collections4/bag/HashBagTest.java | 10 +-
.../collections4/bag/PredicatedBagTest.java | 58 +-
.../collections4/bag/PredicatedSortedBagTest.java | 22 +-
.../collections4/bag/SynchronizedBagTest.java | 10 +-
.../collections4/bag/TransformedBagTest.java | 18 +-
.../collections4/bag/TransformedSortedBagTest.java | 10 +-
.../commons/collections4/bag/TreeBagTest.java | 10 +-
.../collections4/bag/UnmodifiableBagTest.java | 38 +-
.../bag/UnmodifiableSortedBagTest.java | 36 +-
.../collections4/bidimap/AbstractBidiMapTest.java | 734 ++--
.../AbstractOrderedBidiMapDecoratorTest.java | 64 +-
.../bidimap/AbstractOrderedBidiMapTest.java | 132 +-
.../bidimap/AbstractSortedBidiMapTest.java | 442 +--
.../collections4/bidimap/DualHashBidiMapTest.java | 14 +-
.../bidimap/DualLinkedHashBidiMapTest.java | 16 +-
.../collections4/bidimap/DualTreeBidiMap2Test.java | 90 +-
.../collections4/bidimap/DualTreeBidiMapTest.java | 14 +-
.../collections4/bidimap/TreeBidiMapTest.java | 18 +-
.../bidimap/UnmodifiableBidiMapTest.java | 40 +-
.../bidimap/UnmodifiableOrderedBidiMapTest.java | 42 +-
.../bidimap/UnmodifiableSortedBidiMapTest.java | 54 +-
.../bloomfilter/AbstractBitMapProducerTest.java | 76 +-
.../AbstractBloomFilterProducerTest.java | 66 +-
.../bloomfilter/AbstractBloomFilterTest.java | 418 +--
.../bloomfilter/AbstractCellProducerTest.java | 128 +-
.../AbstractCountingBloomFilterTest.java | 342 +-
.../bloomfilter/AbstractHasherTest.java | 22 +-
.../bloomfilter/AbstractIndexProducerTest.java | 146 +-
.../collections4/bloomfilter/ArrayHasher.java | 24 +-
...apProducerFromArrayCountingBloomFilterTest.java | 10 +-
.../BitMapProducerFromIndexProducerTest.java | 10 +-
.../BitMapProducerFromLayeredBloomFilterTest.java | 10 +-
.../BitMapProducerFromLongArrayTest.java | 30 +-
.../BitMapProducerFromSimpleBloomFilterTest.java | 10 +-
.../BitMapProducerFromSparseBloomFilterTest.java | 10 +-
.../BitMapProducerFromWrappedBloomFilterTest.java | 12 +-
.../collections4/bloomfilter/BitMapTest.java | 102 +-
...llProducerFromArrayCountingBloomFilterTest.java | 10 +-
.../CellProducerFromDefaultIndexProducerTest.java | 8 +-
.../CellProducerFromLayeredBloomFilterTest.java | 10 +-
.../bloomfilter/CountingPredicateTest.java | 70 +-
.../bloomfilter/DefaultBitMapProducerTest.java | 62 +-
.../bloomfilter/DefaultBloomFilterTest.java | 304 +-
.../bloomfilter/DefaultCellProducerTest.java | 18 +-
.../bloomfilter/DefaultIndexProducerTest.java | 108 +-
.../bloomfilter/EnhancedDoubleHasherTest.java | 14 +-
.../bloomfilter/IncrementingHasher.java | 28 +-
.../collections4/bloomfilter/IndexFilterTest.java | 34 +-
...exProducerFromArrayCountingBloomFilterTest.java | 14 +-
.../IndexProducerFromBitmapProducerTest.java | 46 +-
.../bloomfilter/IndexProducerFromHasherTest.java | 8 +-
.../bloomfilter/IndexProducerFromIntArrayTest.java | 8 +-
.../IndexProducerFromSimpleBloomFilterTest.java | 14 +-
.../IndexProducerFromSparseBloomFilterTest.java | 14 +-
.../IndexProducerFromUniqueHasherTest.java | 14 +-
.../bloomfilter/IndexProducerTest.java | 36 +-
.../collections4/bloomfilter/LayerManagerTest.java | 256 +-
.../bloomfilter/LayeredBloomFilterTest.java | 358 +-
.../collections4/bloomfilter/NullHasher.java | 10 +-
.../bloomfilter/SetOperationsTest.java | 108 +-
.../collections4/bloomfilter/ShapeTest.java | 246 +-
.../collections4/bloomfilter/TestingHashers.java | 30 +-
.../collection/AbstractCollectionTest.java | 926 +++---
.../collection/CompositeCollectionTest.java | 74 +-
.../collection/IndexedCollectionTest.java | 54 +-
.../PredicatedCollectionBuilderTest.java | 68 +-
.../collection/PredicatedCollectionTest.java | 34 +-
.../collection/SynchronizedCollectionTest.java | 8 +-
.../collection/TransformedCollectionTest.java | 34 +-
.../UnmodifiableBoundedCollectionTest.java | 44 +-
.../collection/UnmodifiableCollectionTest.java | 36 +-
.../comparators/AbstractComparatorTest.java | 164 +-
.../comparators/AbstractNullComparatorTest.java | 32 +-
.../comparators/BooleanComparatorTest.java | 88 +-
.../comparators/ComparableComparatorTest.java | 10 +-
.../comparators/ComparatorChainTest.java | 194 +-
.../comparators/FixedOrderComparatorTest.java | 132 +-
.../comparators/ReverseComparatorTest.java | 40 +-
.../comparators/TransformingComparatorTest.java | 22 +-
.../collections4/functors/AbstractClosureTest.java | 10 +-
.../functors/AbstractCompositePredicateTest.java | 78 +-
.../functors/AbstractMockPredicateTest.java | 48 +-
.../functors/AbstractPredicateTest.java | 26 +-
.../collections4/functors/AllPredicateTest.java | 42 +-
.../functors/CatchAndRethrowClosureTest.java | 6 +-
.../functors/ComparatorPredicateTest.java | 28 +-
.../collections4/functors/EqualPredicateTest.java | 26 +-
.../collections4/functors/NullPredicateTest.java | 14 +-
.../iterators/AbstractIteratorTest.java | 14 +-
.../iterators/AbstractListIteratorTest.java | 188 +-
.../iterators/AbstractMapIteratorTest.java | 154 +-
.../collections4/iterators/ArrayIterator2Test.java | 56 +-
.../iterators/ArrayListIterator2Test.java | 20 +-
.../iterators/ArrayListIteratorTest.java | 8 +-
.../iterators/BoundedIteratorTest.java | 190 +-
.../iterators/CollatingIteratorTest.java | 142 +-
.../collections4/iterators/FilterIteratorTest.java | 92 +-
.../iterators/FilterListIteratorTest.java | 190 +-
.../collections4/iterators/IteratorChainTest.java | 122 +-
.../iterators/LazyIteratorChainTest.java | 144 +-
.../iterators/ListIteratorWrapper2Test.java | 22 +-
.../iterators/ListIteratorWrapperTest.java | 22 +-
.../iterators/LoopingListIteratorTest.java | 282 +-
.../iterators/NodeListIteratorTest.java | 64 +-
.../iterators/ObjectArrayIteratorTest.java | 24 +-
.../iterators/ObjectArrayListIterator2Test.java | 8 +-
.../iterators/ObjectArrayListIteratorTest.java | 8 +-
.../iterators/ObjectGraphIteratorTest.java | 362 +-
.../iterators/PeekingIteratorTest.java | 66 +-
.../iterators/PermutationIteratorTest.java | 98 +-
.../iterators/PushbackIteratorTest.java | 40 +-
.../iterators/ReverseListIteratorTest.java | 90 +-
.../iterators/SingletonIterator2Test.java | 4 +-
.../iterators/SingletonIteratorTest.java | 26 +-
.../iterators/SingletonListIteratorTest.java | 4 +-
.../iterators/SkippingIteratorTest.java | 210 +-
.../iterators/UniqueFilterIteratorTest.java | 24 +-
.../iterators/UnmodifiableIteratorTest.java | 28 +-
.../iterators/UnmodifiableListIteratorTest.java | 32 +-
.../iterators/UnmodifiableMapIteratorTest.java | 38 +-
.../UnmodifiableOrderedMapIteratorTest.java | 40 +-
.../iterators/ZippingIteratorTest.java | 106 +-
.../keyvalue/AbstractMapEntryTest.java | 76 +-
.../collections4/keyvalue/DefaultKeyValueTest.java | 40 +-
.../keyvalue/UnmodifiableMapEntryTest.java | 30 +-
.../collections4/list/AbstractLinkedListTest.java | 152 +-
.../collections4/list/AbstractListTest.java | 1198 +++----
.../list/CursorableLinkedListTest.java | 1064 +++---
.../collections4/list/FixedSizeListTest.java | 82 +-
.../commons/collections4/list/GrowthListTest.java | 40 +-
.../commons/collections4/list/LazyListTest.java | 88 +-
.../list/NodeCachingLinkedListTest.java | 84 +-
.../collections4/list/PredicatedListTest.java | 22 +-
.../collections4/list/SetUniqueListTest.java | 58 +-
.../collections4/list/TransformedListTest.java | 70 +-
.../commons/collections4/list/TreeListTest.java | 214 +-
.../collections4/list/UnmodifiableListTest.java | 68 +-
.../collections4/map/AbstractIterableMapTest.java | 152 +-
.../commons/collections4/map/AbstractMapTest.java | 2692 +++++++--------
.../collections4/map/AbstractOrderedMapTest.java | 148 +-
.../collections4/map/AbstractSortedMapTest.java | 472 +--
.../commons/collections4/map/CompositeMapTest.java | 180 +-
.../commons/collections4/map/DefaultedMapTest.java | 44 +-
.../commons/collections4/map/EmptyMapMutator.java | 16 +-
.../commons/collections4/map/FixedSizeMapTest.java | 22 +-
.../collections4/map/FixedSizeSortedMapTest.java | 26 +-
.../commons/collections4/map/Flat3MapTest.java | 892 ++---
.../commons/collections4/map/HashedMapTest.java | 40 +-
.../commons/collections4/map/IdentityMap.java | 120 +-
.../commons/collections4/map/LRUMapTest.java | 632 ++--
.../commons/collections4/map/LazyMapTest.java | 10 +-
.../collections4/map/LazySortedMapTest.java | 46 +-
.../commons/collections4/map/LinkedMapTest.java | 280 +-
.../collections4/map/ListOrderedMap2Test.java | 144 +-
.../collections4/map/ListOrderedMapTest.java | 438 +--
.../commons/collections4/map/MultiKeyMapTest.java | 244 +-
.../collections4/map/MultiValueMapTest.java | 554 ++--
.../collections4/map/PassiveExpiringMapTest.java | 10 +-
.../collections4/map/PredicatedMapTest.java | 10 +-
.../collections4/map/PredicatedSortedMapTest.java | 62 +-
.../commons/collections4/map/ReferenceMapTest.java | 180 +-
.../commons/collections4/map/SingletonMapTest.java | 80 +-
.../collections4/map/StaticBucketMapTest.java | 44 +-
.../collections4/map/TransformedMapTest.java | 94 +-
.../collections4/map/TransformedSortedMapTest.java | 102 +-
.../collections4/map/UnmodifiableMapTest.java | 22 +-
.../map/UnmodifiableOrderedMapTest.java | 22 +-
.../map/UnmodifiableSortedMapTest.java | 48 +-
.../multimap/AbstractMultiValuedMapTest.java | 2032 ++++++------
.../multimap/ArrayListValuedHashMapTest.java | 160 +-
.../multimap/HashSetValuedHashMapTest.java | 166 +-
.../multimap/TransformedMultiValuedMapTest.java | 98 +-
.../multimap/UnmodifiableMultiValuedMapTest.java | 136 +-
.../multiset/AbstractMultiSetTest.java | 606 ++--
.../collections4/multiset/HashMultiSetTest.java | 10 +-
.../multiset/PredicatedMultiSetTest.java | 60 +-
.../multiset/SynchronizedMultiSetTest.java | 10 +-
.../multiset/UnmodifiableMultiSetTest.java | 52 +-
.../collections4/queue/AbstractQueueTest.java | 280 +-
.../collections4/queue/CircularFifoQueueTest.java | 150 +-
.../collections4/queue/PredicatedQueueTest.java | 32 +-
.../collections4/queue/TransformedQueueTest.java | 22 +-
.../collections4/queue/UnmodifiableQueueTest.java | 58 +-
.../sequence/SequencesComparatorTest.java | 192 +-
.../collections4/set/AbstractNavigableSetTest.java | 354 +-
.../commons/collections4/set/AbstractSetTest.java | 60 +-
.../collections4/set/AbstractSortedSetTest.java | 352 +-
.../commons/collections4/set/CompositeSetTest.java | 170 +-
.../commons/collections4/set/EmptySetMutator.java | 10 +-
.../collections4/set/ListOrderedSet2Test.java | 118 +-
.../collections4/set/ListOrderedSetTest.java | 238 +-
.../collections4/set/MapBackedSet2Test.java | 20 +-
.../commons/collections4/set/MapBackedSetTest.java | 8 +-
.../set/PredicatedNavigableSetTest.java | 36 +-
.../collections4/set/PredicatedSetTest.java | 32 +-
.../collections4/set/PredicatedSortedSetTest.java | 36 +-
.../set/TransformedNavigableSetTest.java | 18 +-
.../collections4/set/TransformedSetTest.java | 30 +-
.../collections4/set/TransformedSortedSetTest.java | 16 +-
.../set/UnmodifiableNavigableSetTest.java | 54 +-
.../collections4/set/UnmodifiableSetTest.java | 34 +-
.../set/UnmodifiableSortedSetTest.java | 56 +-
.../splitmap/TransformedSplitMapTest.java | 110 +-
.../collections4/trie/PatriciaTrie2Test.java | 8 +-
.../collections4/trie/PatriciaTrieTest.java | 136 +-
.../collections4/trie/UnmodifiableTrieTest.java | 38 +-
492 files changed, 41472 insertions(+), 41472 deletions(-)
diff --git a/src/main/java/org/apache/commons/collections4/ArrayUtils.java b/src/main/java/org/apache/commons/collections4/ArrayUtils.java
index 45d670616..9bfe1e800 100644
--- a/src/main/java/org/apache/commons/collections4/ArrayUtils.java
+++ b/src/main/java/org/apache/commons/collections4/ArrayUtils.java
@@ -36,12 +36,6 @@ package org.apache.commons.collections4;
*/
final class ArrayUtils {
- /**
- * Don't allow instances.
- */
- private ArrayUtils() {
- }
-
/**
* <p>
* Checks if the object is in the given array.
@@ -58,22 +52,6 @@ final class ArrayUtils {
return indexOf(array, objectToFind) != CollectionUtils.INDEX_NOT_FOUND;
}
- /**
- * <p>
- * Finds the index of the given object in the array.
- * </p>
- * <p>
- * This method returns {@link CollectionUtils#INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
- * </p>
- *
- * @param array the array to search through for the object, may be {@code null}
- * @param objectToFind the object to find, may be {@code null}
- * @return the index of the object within the array, {@link CollectionUtils#INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
- */
- static <T> int indexOf(final T[] array, final Object objectToFind) {
- return indexOf(array, objectToFind, 0);
- }
-
/**
* <p>
* Finds the index of the given object in the array starting at the given index.
@@ -114,4 +92,26 @@ final class ArrayUtils {
return CollectionUtils.INDEX_NOT_FOUND;
}
+ /**
+ * <p>
+ * Finds the index of the given object in the array.
+ * </p>
+ * <p>
+ * This method returns {@link CollectionUtils#INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
+ * </p>
+ *
+ * @param array the array to search through for the object, may be {@code null}
+ * @param objectToFind the object to find, may be {@code null}
+ * @return the index of the object within the array, {@link CollectionUtils#INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
+ */
+ static <T> int indexOf(final T[] array, final Object objectToFind) {
+ return indexOf(array, objectToFind, 0);
+ }
+
+ /**
+ * Don't allow instances.
+ */
+ private ArrayUtils() {
+ }
+
}
diff --git a/src/main/java/org/apache/commons/collections4/Bag.java b/src/main/java/org/apache/commons/collections4/Bag.java
index 24958751e..e86b1918c 100644
--- a/src/main/java/org/apache/commons/collections4/Bag.java
+++ b/src/main/java/org/apache/commons/collections4/Bag.java
@@ -46,16 +46,6 @@ import java.util.Set;
*/
public interface Bag<E> extends Collection<E> {
- /**
- * Returns the number of occurrences (cardinality) of the given
- * object currently in the bag. If the object does not exist in the
- * bag, return 0.
- *
- * @param object the object to search for
- * @return the number of occurrences of the object, zero if not found
- */
- int getCount(Object object);
-
/**
* <i>(Violation)</i>
* Adds one copy of the specified object to the Bag.
@@ -91,6 +81,47 @@ public interface Bag<E> extends Collection<E> {
*/
boolean add(E object, int nCopies);
+ /**
+ * <i>(Violation)</i>
+ * Returns {@code true} if the bag contains all elements in
+ * the given collection, respecting cardinality. That is, if the
+ * given collection {@code coll} contains {@code n} copies
+ * of a given object, calling {@link #getCount(Object)} on that object must
+ * be {@code >= n} for all {@code n} in {@code coll}.
+ *
+ * <p>
+ * The {@link Collection#containsAll(Collection)} method specifies
+ * that cardinality should <i>not</i> be respected; this method should
+ * return true if the bag contains at least one of every object contained
+ * in the given collection.
+ * </p>
+ *
+ * @param coll the collection to check against
+ * @return {@code true} if the Bag contains all the collection
+ */
+ @Override
+ boolean containsAll(Collection<?> coll);
+
+ /**
+ * Returns the number of occurrences (cardinality) of the given
+ * object currently in the bag. If the object does not exist in the
+ * bag, return 0.
+ *
+ * @param object the object to search for
+ * @return the number of occurrences of the object, zero if not found
+ */
+ int getCount(Object object);
+
+ /**
+ * Returns an {@link Iterator} over the entire set of members,
+ * including copies due to cardinality. This iterator is fail-fast
+ * and will not tolerate concurrent modifications.
+ *
+ * @return iterator over all elements in the Bag
+ */
+ @Override
+ Iterator<E> iterator();
+
/**
* <i>(Violation)</i>
* Removes all occurrences of the given object from the bag.
@@ -122,45 +153,6 @@ public interface Bag<E> extends Collection<E> {
*/
boolean remove(Object object, int nCopies);
- /**
- * Returns a {@link Set} of unique elements in the Bag.
- * <p>
- * Uniqueness constraints are the same as those in {@link java.util.Set}.
- * </p>
- *
- * @return the Set of unique Bag elements
- */
- Set<E> uniqueSet();
-
- /**
- * Returns the total number of items in the bag across all types.
- *
- * @return the total size of the Bag
- */
- @Override
- int size();
-
- /**
- * <i>(Violation)</i>
- * Returns {@code true} if the bag contains all elements in
- * the given collection, respecting cardinality. That is, if the
- * given collection {@code coll} contains {@code n} copies
- * of a given object, calling {@link #getCount(Object)} on that object must
- * be {@code >= n} for all {@code n} in {@code coll}.
- *
- * <p>
- * The {@link Collection#containsAll(Collection)} method specifies
- * that cardinality should <i>not</i> be respected; this method should
- * return true if the bag contains at least one of every object contained
- * in the given collection.
- * </p>
- *
- * @param coll the collection to check against
- * @return {@code true} if the Bag contains all the collection
- */
- @Override
- boolean containsAll(Collection<?> coll);
-
/**
* <i>(Violation)</i>
* Remove all elements represented in the given collection,
@@ -207,14 +199,22 @@ public interface Bag<E> extends Collection<E> {
boolean retainAll(Collection<?> coll);
/**
- * Returns an {@link Iterator} over the entire set of members,
- * including copies due to cardinality. This iterator is fail-fast
- * and will not tolerate concurrent modifications.
+ * Returns the total number of items in the bag across all types.
*
- * @return iterator over all elements in the Bag
+ * @return the total size of the Bag
*/
@Override
- Iterator<E> iterator();
+ int size();
+
+ /**
+ * Returns a {@link Set} of unique elements in the Bag.
+ * <p>
+ * Uniqueness constraints are the same as those in {@link java.util.Set}.
+ * </p>
+ *
+ * @return the Set of unique Bag elements
+ */
+ Set<E> uniqueSet();
// The following is not part of the formal Bag interface, however where possible
// Bag implementations should follow these comments.
diff --git a/src/main/java/org/apache/commons/collections4/BagUtils.java b/src/main/java/org/apache/commons/collections4/BagUtils.java
index 9e5066d13..225437a23 100644
--- a/src/main/java/org/apache/commons/collections4/BagUtils.java
+++ b/src/main/java/org/apache/commons/collections4/BagUtils.java
@@ -49,52 +49,38 @@ public class BagUtils {
UnmodifiableSortedBag.unmodifiableSortedBag(new TreeBag<>());
/**
- * Don't allow instances.
+ * Returns a bag that complies to the Collection contract, backed by the given bag.
+ *
+ * @param <E> the element type
+ * @param bag the bag to decorate, must not be null
+ * @return a Bag that complies to the Collection contract
+ * @throws NullPointerException if bag is null
+ * @since 4.0
*/
- private BagUtils() {}
+ public static <E> Bag<E> collectionBag(final Bag<E> bag) {
+ return CollectionBag.collectionBag(bag);
+ }
/**
- * Returns a synchronized (thread-safe) bag backed by the given bag. In
- * order to guarantee serial access, it is critical that all access to the
- * backing bag is accomplished through the returned bag.
- * <p>
- * It is imperative that the user manually synchronize on the returned bag
- * when iterating over it:
- * </p>
- *
- * <pre>
- * Bag bag = BagUtils.synchronizedBag(new HashBag());
- * ...
- * synchronized(bag) {
- * Iterator i = bag.iterator(); // Must be in synchronized block
- * while (i.hasNext())
- * foo(i.next());
- * }
- * }
- * </pre>
- *
- * Failure to follow this advice may result in non-deterministic behavior.
+ * Gets an empty {@code Bag}.
*
* @param <E> the element type
- * @param bag the bag to synchronize, must not be null
- * @return a synchronized bag backed by that bag
- * @throws NullPointerException if the Bag is null
+ * @return an empty Bag
*/
- public static <E> Bag<E> synchronizedBag(final Bag<E> bag) {
- return SynchronizedBag.synchronizedBag(bag);
+ @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type
+ public static <E> Bag<E> emptyBag() {
+ return EMPTY_BAG;
}
/**
- * Returns an unmodifiable view of the given bag. Any modification attempts
- * to the returned bag will raise an {@link UnsupportedOperationException}.
+ * Gets an empty {@code SortedBag}.
*
* @param <E> the element type
- * @param bag the bag whose unmodifiable view is to be returned, must not be null
- * @return an unmodifiable view of that bag
- * @throws NullPointerException if the Bag is null
+ * @return an empty sorted Bag
*/
- public static <E> Bag<E> unmodifiableBag(final Bag<? extends E> bag) {
- return UnmodifiableBag.unmodifiableBag(bag);
+ @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type
+ public static <E> SortedBag<E> emptySortedBag() {
+ return (SortedBag<E>) EMPTY_SORTED_BAG;
}
/**
@@ -118,38 +104,56 @@ public class BagUtils {
}
/**
- * Returns a transformed bag backed by the given bag.
- * <p>
- * Each object is passed through the transformer as it is added to the Bag.
- * It is important not to use the original bag after invoking this method,
- * as it is a backdoor for adding untransformed objects.
- * </p>
+ * Returns a predicated (validating) sorted bag backed by the given sorted
+ * bag.
* <p>
- * Existing entries in the specified bag will not be transformed.
- * If you want that behavior, see {@link TransformedBag#transformedBag(Bag, Transformer)}.
+ * Only objects that pass the test in the given predicate can be added to
+ * the bag. Trying to add an invalid object results in an
+ * IllegalArgumentException. It is important not to use the original bag
+ * after invoking this method, as it is a backdoor for adding invalid
+ * objects.
* </p>
*
* @param <E> the element type
- * @param bag the bag to predicate, must not be null
- * @param transformer the transformer for the bag, must not be null
- * @return a transformed bag backed by the given bag
- * @throws NullPointerException if the Bag or Transformer is null
+ * @param bag the sorted bag to predicate, must not be null
+ * @param predicate the predicate for the bag, must not be null
+ * @return a predicated bag backed by the given bag
+ * @throws NullPointerException if the SortedBag or Predicate is null
*/
- public static <E> Bag<E> transformingBag(final Bag<E> bag, final Transformer<? super E, ? extends E> transformer) {
- return TransformedBag.transformingBag(bag, transformer);
+ public static <E> SortedBag<E> predicatedSortedBag(final SortedBag<E> bag,
+ final Predicate<? super E> predicate) {
+ return PredicatedSortedBag.predicatedSortedBag(bag, predicate);
}
/**
- * Returns a bag that complies to the Collection contract, backed by the given bag.
+ * Returns a synchronized (thread-safe) bag backed by the given bag. In
+ * order to guarantee serial access, it is critical that all access to the
+ * backing bag is accomplished through the returned bag.
+ * <p>
+ * It is imperative that the user manually synchronize on the returned bag
+ * when iterating over it:
+ * </p>
+ *
+ * <pre>
+ * Bag bag = BagUtils.synchronizedBag(new HashBag());
+ * ...
+ * synchronized(bag) {
+ * Iterator i = bag.iterator(); // Must be in synchronized block
+ * while (i.hasNext())
+ * foo(i.next());
+ * }
+ * }
+ * </pre>
+ *
+ * Failure to follow this advice may result in non-deterministic behavior.
*
* @param <E> the element type
- * @param bag the bag to decorate, must not be null
- * @return a Bag that complies to the Collection contract
- * @throws NullPointerException if bag is null
- * @since 4.0
+ * @param bag the bag to synchronize, must not be null
+ * @return a synchronized bag backed by that bag
+ * @throws NullPointerException if the Bag is null
*/
- public static <E> Bag<E> collectionBag(final Bag<E> bag) {
- return CollectionBag.collectionBag(bag);
+ public static <E> Bag<E> synchronizedBag(final Bag<E> bag) {
+ return SynchronizedBag.synchronizedBag(bag);
}
/**
@@ -184,39 +188,25 @@ public class BagUtils {
}
/**
- * Returns an unmodifiable view of the given sorted bag. Any modification
- * attempts to the returned bag will raise an
- * {@link UnsupportedOperationException}.
- *
- * @param <E> the element type
- * @param bag the bag whose unmodifiable view is to be returned, must not be null
- * @return an unmodifiable view of that bag
- * @throws NullPointerException if the SortedBag is null
- */
- public static <E> SortedBag<E> unmodifiableSortedBag(final SortedBag<E> bag) {
- return UnmodifiableSortedBag.unmodifiableSortedBag(bag);
- }
-
- /**
- * Returns a predicated (validating) sorted bag backed by the given sorted
- * bag.
+ * Returns a transformed bag backed by the given bag.
* <p>
- * Only objects that pass the test in the given predicate can be added to
- * the bag. Trying to add an invalid object results in an
- * IllegalArgumentException. It is important not to use the original bag
- * after invoking this method, as it is a backdoor for adding invalid
- * objects.
+ * Each object is passed through the transformer as it is added to the Bag.
+ * It is important not to use the original bag after invoking this method,
+ * as it is a backdoor for adding untransformed objects.
+ * </p>
+ * <p>
+ * Existing entries in the specified bag will not be transformed.
+ * If you want that behavior, see {@link TransformedBag#transformedBag(Bag, Transformer)}.
* </p>
*
* @param <E> the element type
- * @param bag the sorted bag to predicate, must not be null
- * @param predicate the predicate for the bag, must not be null
- * @return a predicated bag backed by the given bag
- * @throws NullPointerException if the SortedBag or Predicate is null
+ * @param bag the bag to predicate, must not be null
+ * @param transformer the transformer for the bag, must not be null
+ * @return a transformed bag backed by the given bag
+ * @throws NullPointerException if the Bag or Transformer is null
*/
- public static <E> SortedBag<E> predicatedSortedBag(final SortedBag<E> bag,
- final Predicate<? super E> predicate) {
- return PredicatedSortedBag.predicatedSortedBag(bag, predicate);
+ public static <E> Bag<E> transformingBag(final Bag<E> bag, final Transformer<? super E, ? extends E> transformer) {
+ return TransformedBag.transformingBag(bag, transformer);
}
/**
@@ -244,24 +234,34 @@ public class BagUtils {
}
/**
- * Gets an empty {@code Bag}.
+ * Returns an unmodifiable view of the given bag. Any modification attempts
+ * to the returned bag will raise an {@link UnsupportedOperationException}.
*
* @param <E> the element type
- * @return an empty Bag
+ * @param bag the bag whose unmodifiable view is to be returned, must not be null
+ * @return an unmodifiable view of that bag
+ * @throws NullPointerException if the Bag is null
*/
- @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type
- public static <E> Bag<E> emptyBag() {
- return EMPTY_BAG;
+ public static <E> Bag<E> unmodifiableBag(final Bag<? extends E> bag) {
+ return UnmodifiableBag.unmodifiableBag(bag);
}
/**
- * Gets an empty {@code SortedBag}.
+ * Returns an unmodifiable view of the given sorted bag. Any modification
+ * attempts to the returned bag will raise an
+ * {@link UnsupportedOperationException}.
*
* @param <E> the element type
- * @return an empty sorted Bag
+ * @param bag the bag whose unmodifiable view is to be returned, must not be null
+ * @return an unmodifiable view of that bag
+ * @throws NullPointerException if the SortedBag is null
*/
- @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type
- public static <E> SortedBag<E> emptySortedBag() {
- return (SortedBag<E>) EMPTY_SORTED_BAG;
+ public static <E> SortedBag<E> unmodifiableSortedBag(final SortedBag<E> bag) {
+ return UnmodifiableSortedBag.unmodifiableSortedBag(bag);
}
+
+ /**
+ * Don't allow instances.
+ */
+ private BagUtils() {}
}
diff --git a/src/main/java/org/apache/commons/collections4/BidiMap.java b/src/main/java/org/apache/commons/collections4/BidiMap.java
index 5834ae40d..5f04ae6ba 100644
--- a/src/main/java/org/apache/commons/collections4/BidiMap.java
+++ b/src/main/java/org/apache/commons/collections4/BidiMap.java
@@ -45,6 +45,42 @@ import java.util.Set;
*/
public interface BidiMap<K, V> extends IterableMap<K, V> {
+ /**
+ * Gets the key that is currently mapped to the specified value.
+ * <p>
+ * If the value is not contained in the map, {@code null} is returned.
+ * </p>
+ * <p>
+ * Implementations should seek to make this method perform equally as well
+ * as {@code get(Object)}.
+ * </p>
+ *
+ * @param value the value to find the key for
+ * @return the mapped key, or {@code null} if not found
+ *
+ * @throws ClassCastException (optional) if the map limits the type of the
+ * value and the specified value is inappropriate
+ * @throws NullPointerException (optional) if the map limits the values to
+ * non-null and null was specified
+ */
+ K getKey(Object value);
+
+ /**
+ * Gets a view of this map where the keys and values are reversed.
+ * <p>
+ * Changes to one map will be visible in the other and vice versa.
+ * This enables both directions of the map to be accessed as a {@code Map}.
+ * </p>
+ * <p>
+ * Implementations should seek to avoid creating a new object every time this
+ * method is called. See {@code AbstractMap.values()} etc. Calling this
+ * method on the inverse map should return the original.
+ * </p>
+ *
+ * @return an inverted bidirectional map
+ */
+ BidiMap<V, K> inverseBidiMap();
+
/**
* Puts the key-value pair into the map, replacing any previous pair.
* <p>
@@ -77,26 +113,6 @@ public interface BidiMap<K, V> extends IterableMap<K, V> {
@Override
V put(K key, V value);
- /**
- * Gets the key that is currently mapped to the specified value.
- * <p>
- * If the value is not contained in the map, {@code null} is returned.
- * </p>
- * <p>
- * Implementations should seek to make this method perform equally as well
- * as {@code get(Object)}.
- * </p>
- *
- * @param value the value to find the key for
- * @return the mapped key, or {@code null} if not found
- *
- * @throws ClassCastException (optional) if the map limits the type of the
- * value and the specified value is inappropriate
- * @throws NullPointerException (optional) if the map limits the values to
- * non-null and null was specified
- */
- K getKey(Object value);
-
/**
* Removes the key-value pair that is currently mapped to the specified
* value (optional operation).
@@ -120,22 +136,6 @@ public interface BidiMap<K, V> extends IterableMap<K, V> {
*/
K removeValue(Object value);
- /**
- * Gets a view of this map where the keys and values are reversed.
- * <p>
- * Changes to one map will be visible in the other and vice versa.
- * This enables both directions of the map to be accessed as a {@code Map}.
- * </p>
- * <p>
- * Implementations should seek to avoid creating a new object every time this
- * method is called. See {@code AbstractMap.values()} etc. Calling this
- * method on the inverse map should return the original.
- * </p>
- *
- * @return an inverted bidirectional map
- */
- BidiMap<V, K> inverseBidiMap();
-
/**
* Returns a {@link Set} view of the values contained in this map.
* The set is backed by the map, so changes to the map are reflected
diff --git a/src/main/java/org/apache/commons/collections4/ClosureUtils.java b/src/main/java/org/apache/commons/collections4/ClosureUtils.java
index 59f7203ee..819e44416 100644
--- a/src/main/java/org/apache/commons/collections4/ClosureUtils.java
+++ b/src/main/java/org/apache/commons/collections4/ClosureUtils.java
@@ -61,49 +61,82 @@ import org.apache.commons.collections4.functors.WhileClosure;
public class ClosureUtils {
/**
- * Don't allow instances.
+ * Creates a Closure that calls a Transformer each time it is called.
+ * The transformer will be called using the closure's input object.
+ * The transformer's result will be ignored.
+ *
+ * @see org.apache.commons.collections4.functors.TransformerClosure
+ *
+ * @param <E> the type that the closure acts on
+ * @param transformer the transformer to run each time in the closure, null means nop
+ * @return the closure
*/
- private ClosureUtils() {}
+ public static <E> Closure<E> asClosure(final Transformer<? super E, ?> transformer) {
+ return TransformerClosure.transformerClosure(transformer);
+ }
/**
- * Gets a Closure that always throws an exception.
- * This could be useful during testing as a placeholder.
+ * Create a new Closure that calls each closure in turn, passing the
+ * result into the next closure.
*
- * @see org.apache.commons.collections4.functors.ExceptionClosure
+ * @see org.apache.commons.collections4.functors.ChainedClosure
*
* @param <E> the type that the closure acts on
- * @return the closure
+ * @param closures an array of closures to chain
+ * @return the {@code chained} closure
+ * @throws NullPointerException if the closures array is null
+ * @throws NullPointerException if any closure in the array is null
*/
- public static <E> Closure<E> exceptionClosure() {
- return ExceptionClosure.<E>exceptionClosure();
+ public static <E> Closure<E> chainedClosure(final Closure<? super E>... closures) {
+ return ChainedClosure.chainedClosure(closures);
}
/**
- * Gets a Closure that will do nothing.
- * This could be useful during testing as a placeholder.
+ * Create a new Closure that calls each closure in turn, passing the
+ * result into the next closure. The ordering is that of the iterator()
+ * method on the collection.
*
- * @see org.apache.commons.collections4.functors.NOPClosure
+ * @see org.apache.commons.collections4.functors.ChainedClosure
*
* @param <E> the type that the closure acts on
- * @return the closure
+ * @param closures a collection of closures to chain
+ * @return the {@code chained} closure
+ * @throws NullPointerException if the closures collection is null
+ * @throws NullPointerException if any closure in the collection is null
+ * @throws IllegalArgumentException if the closures collection is empty
*/
- public static <E> Closure<E> nopClosure() {
- return NOPClosure.<E>nopClosure();
+ public static <E> Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures) {
+ return ChainedClosure.chainedClosure(closures);
}
/**
- * Creates a Closure that calls a Transformer each time it is called.
- * The transformer will be called using the closure's input object.
- * The transformer's result will be ignored.
+ * Creates a Closure that will call the closure once and then repeatedly
+ * until the predicate returns false.
*
- * @see org.apache.commons.collections4.functors.TransformerClosure
+ * @see org.apache.commons.collections4.functors.WhileClosure
+ *
+ * @param <E> the type that the closure acts on
+ * @param closure the closure to call repeatedly, not null
+ * @param predicate the predicate to use as an end of loop test, not null
+ * @return the {@code do-while} closure
+ * @throws NullPointerException if either argument is null
+ */
+ public static <E> Closure<E> doWhileClosure(final Closure<? super E> closure,
+ final Predicate<? super E> predicate) {
+ return WhileClosure.<E>whileClosure(predicate, closure, true);
+ }
+
+ /**
+ * Gets a Closure that always throws an exception.
+ * This could be useful during testing as a placeholder.
+ *
+ * @see org.apache.commons.collections4.functors.ExceptionClosure
*
* @param <E> the type that the closure acts on
- * @param transformer the transformer to run each time in the closure, null means nop
* @return the closure
*/
- public static <E> Closure<E> asClosure(final Transformer<? super E, ?> transformer) {
- return TransformerClosure.transformerClosure(transformer);
+ public static <E> Closure<E> exceptionClosure() {
+ return ExceptionClosure.<E>exceptionClosure();
}
/**
@@ -123,36 +156,40 @@ public class ClosureUtils {
}
/**
- * Creates a Closure that will call the closure repeatedly until the
- * predicate returns false.
+ * Create a new Closure that calls another closure based on the
+ * result of the specified predicate.
*
- * @see org.apache.commons.collections4.functors.WhileClosure
+ * @see org.apache.commons.collections4.functors.IfClosure
*
* @param <E> the type that the closure acts on
- * @param predicate the predicate to use as an end of loop test, not null
- * @param closure the closure to call repeatedly, not null
- * @return the {@code while} closure
- * @throws NullPointerException if either argument is null
+ * @param predicate the validating predicate
+ * @param trueClosure the closure called if the predicate is true
+ * @return the {@code if} closure
+ * @throws NullPointerException if the predicate or closure is null
+ * @since 3.2
*/
- public static <E> Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure) {
- return WhileClosure.<E>whileClosure(predicate, closure, false);
+ public static <E> Closure<E> ifClosure(final Predicate<? super E> predicate,
+ final Closure<? super E> trueClosure) {
+ return IfClosure.<E>ifClosure(predicate, trueClosure);
}
/**
- * Creates a Closure that will call the closure once and then repeatedly
- * until the predicate returns false.
+ * Create a new Closure that calls one of two closures depending
+ * on the specified predicate.
*
- * @see org.apache.commons.collections4.functors.WhileClosure
+ * @see org.apache.commons.collections4.functors.IfClosure
*
* @param <E> the type that the closure acts on
- * @param closure the closure to call repeatedly, not null
- * @param predicate the predicate to use as an end of loop test, not null
- * @return the {@code do-while} closure
- * @throws NullPointerException if either argument is null
+ * @param predicate the predicate to switch on
+ * @param trueClosure the closure called if the predicate is true
+ * @param falseClosure the closure called if the predicate is false
+ * @return the {@code switch} closure
+ * @throws NullPointerException if the predicate or either closure is null
*/
- public static <E> Closure<E> doWhileClosure(final Closure<? super E> closure,
- final Predicate<? super E> predicate) {
- return WhileClosure.<E>whileClosure(predicate, closure, true);
+ public static <E> Closure<E> ifClosure(final Predicate<? super E> predicate,
+ final Closure<? super E> trueClosure,
+ final Closure<? super E> falseClosure) {
+ return IfClosure.<E>ifClosure(predicate, trueClosure, falseClosure);
}
/**
@@ -194,74 +231,41 @@ public class ClosureUtils {
}
/**
- * Create a new Closure that calls each closure in turn, passing the
- * result into the next closure.
- *
- * @see org.apache.commons.collections4.functors.ChainedClosure
- *
- * @param <E> the type that the closure acts on
- * @param closures an array of closures to chain
- * @return the {@code chained} closure
- * @throws NullPointerException if the closures array is null
- * @throws NullPointerException if any closure in the array is null
- */
- public static <E> Closure<E> chainedClosure(final Closure<? super E>... closures) {
- return ChainedClosure.chainedClosure(closures);
- }
-
- /**
- * Create a new Closure that calls each closure in turn, passing the
- * result into the next closure. The ordering is that of the iterator()
- * method on the collection.
- *
- * @see org.apache.commons.collections4.functors.ChainedClosure
- *
- * @param <E> the type that the closure acts on
- * @param closures a collection of closures to chain
- * @return the {@code chained} closure
- * @throws NullPointerException if the closures collection is null
- * @throws NullPointerException if any closure in the collection is null
- * @throws IllegalArgumentException if the closures collection is empty
- */
- public static <E> Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures) {
- return ChainedClosure.chainedClosure(closures);
- }
-
- /**
- * Create a new Closure that calls another closure based on the
- * result of the specified predicate.
+ * Gets a Closure that will do nothing.
+ * This could be useful during testing as a placeholder.
*
- * @see org.apache.commons.collections4.functors.IfClosure
+ * @see org.apache.commons.collections4.functors.NOPClosure
*
* @param <E> the type that the closure acts on
- * @param predicate the validating predicate
- * @param trueClosure the closure called if the predicate is true
- * @return the {@code if} closure
- * @throws NullPointerException if the predicate or closure is null
- * @since 3.2
+ * @return the closure
*/
- public static <E> Closure<E> ifClosure(final Predicate<? super E> predicate,
- final Closure<? super E> trueClosure) {
- return IfClosure.<E>ifClosure(predicate, trueClosure);
+ public static <E> Closure<E> nopClosure() {
+ return NOPClosure.<E>nopClosure();
}
/**
- * Create a new Closure that calls one of two closures depending
- * on the specified predicate.
+ * Create a new Closure that calls one of the closures depending
+ * on the predicates.
+ * <p>
+ * The Map consists of Predicate keys and Closure values. A closure
+ * is called if its matching predicate returns true. Each predicate is evaluated
+ * until one returns true. If no predicates evaluate to true, the default
+ * closure is called. The default closure is set in the map with a
+ * null key. The ordering is that of the iterator() method on the entryset
+ * collection of the map.
*
- * @see org.apache.commons.collections4.functors.IfClosure
+ * @see org.apache.commons.collections4.functors.SwitchClosure
*
* @param <E> the type that the closure acts on
- * @param predicate the predicate to switch on
- * @param trueClosure the closure called if the predicate is true
- * @param falseClosure the closure called if the predicate is false
+ * @param predicatesAndClosures a map of predicates to closures
* @return the {@code switch} closure
- * @throws NullPointerException if the predicate or either closure is null
+ * @throws NullPointerException if the map is null
+ * @throws NullPointerException if any closure in the map is null
+ * @throws IllegalArgumentException if the map is empty
+ * @throws ClassCastException if the map elements are of the wrong type
*/
- public static <E> Closure<E> ifClosure(final Predicate<? super E> predicate,
- final Closure<? super E> trueClosure,
- final Closure<? super E> falseClosure) {
- return IfClosure.<E>ifClosure(predicate, trueClosure, falseClosure);
+ public static <E> Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures) {
+ return SwitchClosure.switchClosure(predicatesAndClosures);
}
/**
@@ -313,31 +317,6 @@ public class ClosureUtils {
return SwitchClosure.<E>switchClosure(predicates, closures, defaultClosure);
}
- /**
- * Create a new Closure that calls one of the closures depending
- * on the predicates.
- * <p>
- * The Map consists of Predicate keys and Closure values. A closure
- * is called if its matching predicate returns true. Each predicate is evaluated
- * until one returns true. If no predicates evaluate to true, the default
- * closure is called. The default closure is set in the map with a
- * null key. The ordering is that of the iterator() method on the entryset
- * collection of the map.
- *
- * @see org.apache.commons.collections4.functors.SwitchClosure
- *
- * @param <E> the type that the closure acts on
- * @param predicatesAndClosures a map of predicates to closures
- * @return the {@code switch} closure
- * @throws NullPointerException if the map is null
- * @throws NullPointerException if any closure in the map is null
- * @throws IllegalArgumentException if the map is empty
- * @throws ClassCastException if the map elements are of the wrong type
- */
- public static <E> Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures) {
- return SwitchClosure.switchClosure(predicatesAndClosures);
- }
-
/**
* Create a new Closure that uses the input object as a key to find the
* closure to call.
@@ -372,4 +351,25 @@ public class ClosureUtils {
return ClosureUtils.<E>switchClosure(preds, trs, def);
}
+ /**
+ * Creates a Closure that will call the closure repeatedly until the
+ * predicate returns false.
+ *
+ * @see org.apache.commons.collections4.functors.WhileClosure
+ *
+ * @param <E> the type that the closure acts on
+ * @param predicate the predicate to use as an end of loop test, not null
+ * @param closure the closure to call repeatedly, not null
+ * @return the {@code while} closure
+ * @throws NullPointerException if either argument is null
+ */
+ public static <E> Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure) {
+ return WhileClosure.<E>whileClosure(predicate, closure, false);
+ }
+
+ /**
+ * Don't allow instances.
+ */
+ private ClosureUtils() {}
+
}
diff --git a/src/main/java/org/apache/commons/collections4/CollectionUtils.java b/src/main/java/org/apache/commons/collections4/CollectionUtils.java
index 1a3e2450d..5a62e9269 100644
--- a/src/main/java/org/apache/commons/collections4/CollectionUtils.java
+++ b/src/main/java/org/apache/commons/collections4/CollectionUtils.java
@@ -56,40 +56,6 @@ import org.apache.commons.collections4.iterators.PermutationIterator;
*/
public class CollectionUtils {
- /**
- * The index value when an element is not found in a collection or array: {@code -1}.
- *
- * @since 4.5
- */
- public static final int INDEX_NOT_FOUND = -1;
-
- /**
- * Default prefix used while converting an Iterator to its String representation.
- *
- * @since 4.5
- */
- public static final String DEFAULT_TOSTRING_PREFIX = "[";
-
- /**
- * Default suffix used while converting an Iterator to its String representation.
- *
- * @since 4.5
- */
- public static final String DEFAULT_TOSTRING_SUFFIX = "]";
-
- /**
- * A String for Colon (":").
- *
- * @since 4.5
- */
- public static final String COLON = ":";
- /**
- * A String for Comma (",").
- *
- * @since 4.5
- */
- public static final String COMMA = ",";
-
/**
* Helper class to easily access cardinality properties of two collections.
* @param <O> the element type
@@ -112,24 +78,6 @@ public class CollectionUtils {
cardinalityB = CollectionUtils.<O>getCardinalityMap(b);
}
- /**
- * Returns the maximum frequency of an object.
- * @param obj the object
- * @return the maximum frequency of the object
- */
- public final int max(final Object obj) {
- return Math.max(freqA(obj), freqB(obj));
- }
-
- /**
- * Returns the minimum frequency of an object.
- * @param obj the object
- * @return the minimum frequency of the object
- */
- public final int min(final Object obj) {
- return Math.min(freqA(obj), freqB(obj));
- }
-
/**
* Returns the frequency of this object in collection A.
* @param obj the object
@@ -155,6 +103,63 @@ public class CollectionUtils {
}
return 0;
}
+
+ /**
+ * Returns the maximum frequency of an object.
+ * @param obj the object
+ * @return the maximum frequency of the object
+ */
+ public final int max(final Object obj) {
+ return Math.max(freqA(obj), freqB(obj));
+ }
+
+ /**
+ * Returns the minimum frequency of an object.
+ * @param obj the object
+ * @return the minimum frequency of the object
+ */
+ public final int min(final Object obj) {
+ return Math.min(freqA(obj), freqB(obj));
+ }
+ }
+
+ /**
+ * Wraps another object and uses the provided Equator to implement
+ * {@link #equals(Object)} and {@link #hashCode()}.
+ * <p>
+ * This class can be used to store objects into a Map.
+ * </p>
+ *
+ * @param <O> the element type
+ * @since 4.0
+ */
+ private static final class EquatorWrapper<O> {
+ private final Equator<? super O> equator;
+ private final O object;
+
+ EquatorWrapper(final Equator<? super O> equator, final O object) {
+ this.equator = equator;
+ this.object = object;
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (!(obj instanceof EquatorWrapper)) {
+ return false;
+ }
+ @SuppressWarnings("unchecked")
+ final EquatorWrapper<O> otherObj = (EquatorWrapper<O>) obj;
+ return equator.equate(object, otherObj.getObject());
+ }
+
+ public O getObject() {
+ return object;
+ }
+
+ @Override
+ public int hashCode() {
+ return equator.hash(object);
+ }
}
/**
@@ -188,6 +193,14 @@ public class CollectionUtils {
return elements.iterator();
}
+ /**
+ * Returns the resulting collection.
+ * @return the result
+ */
+ public Collection<O> list() {
+ return newList;
+ }
+
/**
* Add the object {@code count} times to the result collection.
* @param obj the object to add
@@ -199,16 +212,42 @@ public class CollectionUtils {
}
}
- /**
- * Returns the resulting collection.
- * @return the result
- */
- public Collection<O> list() {
- return newList;
- }
-
}
+ /**
+ * The index value when an element is not found in a collection or array: {@code -1}.
+ *
+ * @since 4.5
+ */
+ public static final int INDEX_NOT_FOUND = -1;
+ /**
+ * Default prefix used while converting an Iterator to its String representation.
+ *
+ * @since 4.5
+ */
+ public static final String DEFAULT_TOSTRING_PREFIX = "[";
+
+ /**
+ * Default suffix used while converting an Iterator to its String representation.
+ *
+ * @since 4.5
+ */
+ public static final String DEFAULT_TOSTRING_SUFFIX = "]";
+
+ /**
+ * A String for Colon (":").
+ *
+ * @since 4.5
+ */
+ public static final String COLON = ":";
+
+ /**
+ * A String for Comma (",").
+ *
+ * @since 4.5
+ */
+ public static final String COMMA = ",";
+
/**
* An empty unmodifiable collection.
* The JDK provides empty Set and List implementations which could be used for
@@ -219,642 +258,563 @@ public class CollectionUtils {
public static final Collection EMPTY_COLLECTION = Collections.emptyList();
/**
- * Don't allow instances.
+ * Adds all elements in the array to the given collection.
+ *
+ * @param <C> the type of object the {@link Collection} contains
+ * @param collection the collection to add to, must not be null
+ * @param elements the array of elements to add, must not be null
+ * @return {@code true} if the collection was changed, {@code false} otherwise
+ * @throws NullPointerException if the collection or elements is null
*/
- private CollectionUtils() {}
+ public static <C> boolean addAll(final Collection<C> collection, final C... elements) {
+ Objects.requireNonNull(collection, "collection");
+ Objects.requireNonNull(elements, "elements");
+ boolean changed = false;
+ for (final C element : elements) {
+ changed |= collection.add(element);
+ }
+ return changed;
+ }
/**
- * Returns the immutable EMPTY_COLLECTION with generic type safety.
+ * Adds all elements in the enumeration to the given collection.
*
- * @see #EMPTY_COLLECTION
- * @since 4.0
- * @param <T> the element type
- * @return immutable empty collection
+ * @param <C> the type of object the {@link Collection} contains
+ * @param collection the collection to add to, must not be null
+ * @param enumeration the enumeration of elements to add, must not be null
+ * @return {@code true} if the collections was changed, {@code false} otherwise
+ * @throws NullPointerException if the collection or enumeration is null
*/
- @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type
- public static <T> Collection<T> emptyCollection() {
- return EMPTY_COLLECTION;
+ public static <C> boolean addAll(final Collection<C> collection, final Enumeration<? extends C> enumeration) {
+ Objects.requireNonNull(collection, "collection");
+ Objects.requireNonNull(enumeration, "enumeration");
+ boolean changed = false;
+ while (enumeration.hasMoreElements()) {
+ changed |= collection.add(enumeration.nextElement());
+ }
+ return changed;
}
/**
- * Returns an immutable empty collection if the argument is {@code null},
- * or the argument itself otherwise.
+ * Adds all elements in the {@link Iterable} to the given collection. If the
+ * {@link Iterable} is a {@link Collection} then it is cast and will be
+ * added using {@link Collection#addAll(Collection)} instead of iterating.
*
- * @param <T> the element type
- * @param collection the collection, possibly {@code null}
- * @return an empty collection if the argument is {@code null}
+ * @param <C> the type of object the {@link Collection} contains
+ * @param collection the collection to add to, must not be null
+ * @param iterable the iterable of elements to add, must not be null
+ * @return a boolean indicating whether the collection has changed or not.
+ * @throws NullPointerException if the collection or iterable is null
*/
- public static <T> Collection<T> emptyIfNull(final Collection<T> collection) {
- return collection == null ? CollectionUtils.<T>emptyCollection() : collection;
+ public static <C> boolean addAll(final Collection<C> collection, final Iterable<? extends C> iterable) {
+ Objects.requireNonNull(collection, "collection");
+ Objects.requireNonNull(iterable, "iterable");
+ if (iterable instanceof Collection<?>) {
+ return collection.addAll((Collection<? extends C>) iterable);
+ }
+ return addAll(collection, iterable.iterator());
}
/**
- * Returns a {@link Collection} containing the union of the given
- * {@link Iterable}s.
- * <p>
- * The cardinality of each element in the returned {@link Collection} will
- * be equal to the maximum of the cardinality of that element in the two
- * given {@link Iterable}s.
- * </p>
+ * Adds all elements in the iteration to the given collection.
*
- * @param a the first collection, must not be null
- * @param b the second collection, must not be null
- * @param <O> the generic type that is able to represent the types contained
- * in both input collections.
- * @return the union of the two collections
- * @throws NullPointerException if either collection is null
- * @see Collection#addAll
+ * @param <C> the type of object the {@link Collection} contains
+ * @param collection the collection to add to, must not be null
+ * @param iterator the iterator of elements to add, must not be null
+ * @return a boolean indicating whether the collection has changed or not.
+ * @throws NullPointerException if the collection or iterator is null
*/
- public static <O> Collection<O> union(final Iterable<? extends O> a, final Iterable<? extends O> b) {
- Objects.requireNonNull(a, "a");
- Objects.requireNonNull(b, "b");
- final SetOperationCardinalityHelper<O> helper = new SetOperationCardinalityHelper<>(a, b);
- for (final O obj : helper) {
- helper.setCardinality(obj, helper.max(obj));
+ public static <C> boolean addAll(final Collection<C> collection, final Iterator<? extends C> iterator) {
+ Objects.requireNonNull(collection, "collection");
+ Objects.requireNonNull(iterator, "iterator");
+ boolean changed = false;
+ while (iterator.hasNext()) {
+ changed |= collection.add(iterator.next());
}
- return helper.list();
+ return changed;
}
/**
- * Returns a {@link Collection} containing the intersection of the given
- * {@link Iterable}s.
- * <p>
- * The cardinality of each element in the returned {@link Collection} will
- * be equal to the minimum of the cardinality of that element in the two
- * given {@link Iterable}s.
- * </p>
+ * Adds an element to the collection unless the element is null.
*
- * @param a the first collection, must not be null
- * @param b the second collection, must not be null
- * @param <O> the generic type that is able to represent the types contained
- * in both input collections.
- * @return the intersection of the two collections
- * @throws NullPointerException if either collection is null
- * @see Collection#retainAll
- * @see #containsAny
+ * @param <T> the type of object the {@link Collection} contains
+ * @param collection the collection to add to, must not be null
+ * @param object the object to add, if null it will not be added
+ * @return true if the collection changed
+ * @throws NullPointerException if the collection is null
+ * @since 3.2
*/
- public static <O> Collection<O> intersection(final Iterable<? extends O> a, final Iterable<? extends O> b) {
- Objects.requireNonNull(a, "a");
- Objects.requireNonNull(b, "b");
- final SetOperationCardinalityHelper<O> helper = new SetOperationCardinalityHelper<>(a, b);
- for (final O obj : helper) {
- helper.setCardinality(obj, helper.min(obj));
- }
- return helper.list();
+ public static <T> boolean addIgnoreNull(final Collection<T> collection, final T object) {
+ Objects.requireNonNull(collection, "collection");
+ return object != null && collection.add(object);
}
/**
- * Returns a {@link Collection} containing the exclusive disjunction
- * (symmetric difference) of the given {@link Iterable}s.
- * <p>
- * The cardinality of each element <i>e</i> in the returned
- * {@link Collection} will be equal to
- * <code>max(cardinality(<i>e</i>,<i>a</i>),cardinality(<i>e</i>,<i>b</i>)) - min(cardinality(<i>e</i>,<i>a</i>),
- * cardinality(<i>e</i>,<i>b</i>))</code>.
- * </p>
- * <p>
- * This is equivalent to
- * {@code {@link #subtract subtract}({@link #union union(a,b)},{@link #intersection intersection(a,b)})}
- * or
- * {@code {@link #union union}({@link #subtract subtract(a,b)},{@link #subtract subtract(b,a)})}.
- * </p>
+ * Returns the number of occurrences of <i>obj</i> in <i>coll</i>.
*
- * @param a the first collection, must not be null
- * @param b the second collection, must not be null
- * @param <O> the generic type that is able to represent the types contained
- * in both input collections.
- * @return the symmetric difference of the two collections
- * @throws NullPointerException if either collection is null
+ * @param obj the object to find the cardinality of
+ * @param collection the {@link Iterable} to search
+ * @param <O> the type of object that the {@link Iterable} may contain.
+ * @return the number of occurrences of obj in coll
+ * @throws NullPointerException if collection is null
+ * @deprecated since 4.1, use {@link IterableUtils#frequency(Iterable, Object)} instead.
+ * Be aware that the order of parameters has changed.
*/
- public static <O> Collection<O> disjunction(final Iterable<? extends O> a, final Iterable<? extends O> b) {
- Objects.requireNonNull(a, "a");
- Objects.requireNonNull(b, "b");
- final SetOperationCardinalityHelper<O> helper = new SetOperationCardinalityHelper<>(a, b);
- for (final O obj : helper) {
- helper.setCardinality(obj, helper.max(obj) - helper.min(obj));
- }
- return helper.list();
+ @Deprecated
+ public static <O> int cardinality(final O obj, final Iterable<? super O> collection) {
+ return IterableUtils.frequency(Objects.requireNonNull(collection, "collection"), obj);
}
/**
- * Returns a new {@link Collection} containing {@code <i>a</i> - <i>b</i>}.
- * The cardinality of each element <i>e</i> in the returned {@link Collection}
- * will be the cardinality of <i>e</i> in <i>a</i> minus the cardinality
- * of <i>e</i> in <i>b</i>, or zero, whichever is greater.
- *
- * @param a the collection to subtract from, must not be null
- * @param b the collection to subtract, must not be null
- * @param <O> the generic type that is able to represent the types contained
- * in both input collections.
- * @return a new collection with the results
- * @see Collection#removeAll
+ * Ensures an index is not negative.
+ * @param index the index to check.
+ * @throws IndexOutOfBoundsException if the index is negative.
*/
- public static <O> Collection<O> subtract(final Iterable<? extends O> a, final Iterable<? extends O> b) {
- final Predicate<O> p = TruePredicate.truePredicate();
- return subtract(a, b, p);
+ static void checkIndexBounds(final int index) {
+ if (index < 0) {
+ throw new IndexOutOfBoundsException("Index cannot be negative: " + index);
+ }
}
/**
- * Returns a new {@link Collection} containing <i>a</i> minus a subset of
- * <i>b</i>. Only the elements of <i>b</i> that satisfy the predicate
- * condition, <i>p</i> are subtracted from <i>a</i>.
- *
- * <p>
- * The cardinality of each element <i>e</i> in the returned {@link Collection}
- * that satisfies the predicate condition will be the cardinality of <i>e</i> in <i>a</i>
- * minus the cardinality of <i>e</i> in <i>b</i>, or zero, whichever is greater.
- * </p>
+ * Merges two sorted Collections, a and b, into a single, sorted List
+ * such that the natural ordering of the elements is retained.
* <p>
- * The cardinality of each element <i>e</i> in the returned {@link Collection} that does <b>not</b>
- * satisfy the predicate condition will be equal to the cardinality of <i>e</i> in <i>a</i>.
+ * Uses the standard O(n) merge algorithm for combining two sorted lists.
* </p>
*
- * @param a the collection to subtract from, must not be null
- * @param b the collection to subtract, must not be null
- * @param p the condition used to determine which elements of <i>b</i> are
- * subtracted.
- * @param <O> the generic type that is able to represent the types contained
- * in both input collections.
- * @return a new collection with the results
- * @throws NullPointerException if either collection or p is null
+ * @param <O> the element type
+ * @param a the first collection, must not be null
+ * @param b the second collection, must not be null
+ * @return a new sorted List, containing the elements of Collection a and b
+ * @throws NullPointerException if either collection is null
* @since 4.0
- * @see Collection#removeAll
*/
- public static <O> Collection<O> subtract(final Iterable<? extends O> a,
- final Iterable<? extends O> b,
- final Predicate<O> p) {
- Objects.requireNonNull(a, "a");
- Objects.requireNonNull(b, "b");
- Objects.requireNonNull(p, "p");
- final ArrayList<O> list = new ArrayList<>();
- final HashBag<O> bag = new HashBag<>();
- for (final O element : b) {
- if (p.evaluate(element)) {
- bag.add(element);
- }
- }
- for (final O element : a) {
- if (!bag.remove(element, 1)) {
- list.add(element);
- }
- }
- return list;
+ public static <O extends Comparable<? super O>> List<O> collate(final Iterable<? extends O> a,
+ final Iterable<? extends O> b) {
+ return collate(a, b, ComparatorUtils.<O>naturalComparator(), true);
}
/**
- * Returns {@code true} iff all elements of {@code coll2} are also contained
- * in {@code coll1}. The cardinality of values in {@code coll2} is not taken into account,
- * which is the same behavior as {@link Collection#containsAll(Collection)}.
- * <p>
- * In other words, this method returns {@code true} iff the
- * {@link #intersection} of <i>coll1</i> and <i>coll2</i> has the same cardinality as
- * the set of unique values from {@code coll2}. In case {@code coll2} is empty, {@code true}
- * will be returned.
- * </p>
+ * Merges two sorted Collections, a and b, into a single, sorted List
+ * such that the natural ordering of the elements is retained.
* <p>
- * This method is intended as a replacement for {@link Collection#containsAll(Collection)}
- * with a guaranteed runtime complexity of {@code O(n + m)}. Depending on the type of
- * {@link Collection} provided, this method will be much faster than calling
- * {@link Collection#containsAll(Collection)} instead, though this will come at the
- * cost of an additional space complexity O(n).
+ * Uses the standard O(n) merge algorithm for combining two sorted lists.
* </p>
*
- * @param coll1 the first collection, must not be null
- * @param coll2 the second collection, must not be null
- * @return {@code true} iff the intersection of the collections has the same cardinality
- * as the set of unique elements from the second collection
- * @throws NullPointerException if coll1 or coll2 is null
+ * @param <O> the element type
+ * @param a the first collection, must not be null
+ * @param b the second collection, must not be null
+ * @param includeDuplicates if {@code true} duplicate elements will be retained, otherwise
+ * they will be removed in the output collection
+ * @return a new sorted List, containing the elements of Collection a and b
+ * @throws NullPointerException if either collection is null
* @since 4.0
*/
- public static boolean containsAll(final Collection<?> coll1, final Collection<?> coll2) {
- Objects.requireNonNull(coll1, "coll1");
- Objects.requireNonNull(coll2, "coll2");
- if (coll2.isEmpty()) {
- return true;
- }
- final Set<Object> elementsAlreadySeen = new HashSet<>();
- for (final Object nextElement : coll2) {
- if (elementsAlreadySeen.contains(nextElement)) {
- continue;
- }
-
- boolean foundCurrentElement = false;
- for (final Object p : coll1) {
- elementsAlreadySeen.add(p);
- if (Objects.equals(nextElement, p)) {
- foundCurrentElement = true;
- break;
- }
- }
-
- if (!foundCurrentElement) {
- return false;
- }
- }
- return true;
+ public static <O extends Comparable<? super O>> List<O> collate(final Iterable<? extends O> a,
+ final Iterable<? extends O> b,
+ final boolean includeDuplicates) {
+ return collate(a, b, ComparatorUtils.<O>naturalComparator(), includeDuplicates);
}
/**
- * Returns {@code true} iff at least one element is in both collections.
+ * Merges two sorted Collections, a and b, into a single, sorted List
+ * such that the ordering of the elements according to Comparator c is retained.
* <p>
- * In other words, this method returns {@code true} iff the
- * {@link #intersection} of <i>coll1</i> and <i>coll2</i> is not empty.
+ * Uses the standard O(n) merge algorithm for combining two sorted lists.
* </p>
*
- * @param <T> the type of object to lookup in {@code coll1}.
- * @param coll1 the first collection, must not be null
- * @param coll2 the second collection, must not be null
- * @return {@code true} iff the intersection of the collections is non-empty
- * @throws NullPointerException if coll1 or coll2 is null
- * @since 4.2
- * @see #intersection
+ * @param <O> the element type
+ * @param a the first collection, must not be null
+ * @param b the second collection, must not be null
+ * @param c the comparator to use for the merge.
+ * @return a new sorted List, containing the elements of Collection a and b
+ * @throws NullPointerException if either collection or the comparator is null
+ * @since 4.0
*/
- public static <T> boolean containsAny(final Collection<?> coll1, @SuppressWarnings("unchecked") final T... coll2) {
- Objects.requireNonNull(coll1, "coll1");
- Objects.requireNonNull(coll2, "coll2");
- if (coll1.size() < coll2.length) {
- for (final Object aColl1 : coll1) {
- if (ArrayUtils.contains(coll2, aColl1)) {
- return true;
- }
- }
- } else {
- for (final Object aColl2 : coll2) {
- if (coll1.contains(aColl2)) {
- return true;
- }
- }
- }
- return false;
+ public static <O> List<O> collate(final Iterable<? extends O> a, final Iterable<? extends O> b,
+ final Comparator<? super O> c) {
+ return collate(a, b, c, true);
}
/**
- * Returns {@code true} iff at least one element is in both collections.
+ * Merges two sorted Collections, a and b, into a single, sorted List
+ * such that the ordering of the elements according to Comparator c is retained.
* <p>
- * In other words, this method returns {@code true} iff the
- * {@link #intersection} of <i>coll1</i> and <i>coll2</i> is not empty.
+ * Uses the standard O(n) merge algorithm for combining two sorted lists.
* </p>
*
- * @param coll1 the first collection, must not be null
- * @param coll2 the second collection, must not be null
- * @return {@code true} iff the intersection of the collections is non-empty
- * @throws NullPointerException if coll1 or coll2 is null
- * @since 2.1
- * @see #intersection
- */
- public static boolean containsAny(final Collection<?> coll1, final Collection<?> coll2) {
- Objects.requireNonNull(coll1, "coll1");
- Objects.requireNonNull(coll2, "coll2");
- if (coll1.size() < coll2.size()) {
- for (final Object aColl1 : coll1) {
- if (coll2.contains(aColl1)) {
- return true;
- }
- }
- } else {
- for (final Object aColl2 : coll2) {
- if (coll1.contains(aColl2)) {
- return true;
- }
+ * @param <O> the element type
+ * @param iterableA the first collection, must not be null
+ * @param iterableB the second collection, must not be null
+ * @param comparator the comparator to use for the merge.
+ * @param includeDuplicates if {@code true} duplicate elements will be retained, otherwise
+ * they will be removed in the output collection
+ * @return a new sorted List, containing the elements of Collection a and b
+ * @throws NullPointerException if either collection or the comparator is null
+ * @since 4.0
+ */
+ public static <O> List<O> collate(final Iterable<? extends O> iterableA, final Iterable<? extends O> iterableB,
+ final Comparator<? super O> comparator, final boolean includeDuplicates) {
+
+ Objects.requireNonNull(iterableA, "iterableA");
+ Objects.requireNonNull(iterableB, "iterableB");
+ Objects.requireNonNull(comparator, "comparator");
+
+ // if both Iterables are a Collection, we can estimate the size
+ final int totalSize = iterableA instanceof Collection<?> && iterableB instanceof Collection<?> ?
+ Math.max(1, ((Collection<?>) iterableA).size() + ((Collection<?>) iterableB).size()) : 10;
+
+ final Iterator<O> iterator = new CollatingIterator<>(comparator, iterableA.iterator(), iterableB.iterator());
+ if (includeDuplicates) {
+ return IteratorUtils.toList(iterator, totalSize);
+ }
+ final ArrayList<O> mergedList = new ArrayList<>(totalSize);
+
+ O lastItem = null;
+ while (iterator.hasNext()) {
+ final O item = iterator.next();
+ if (lastItem == null || !lastItem.equals(item)) {
+ mergedList.add(item);
}
+ lastItem = item;
}
- return false;
+
+ mergedList.trimToSize();
+ return mergedList;
}
/**
- * Returns a {@link Map} mapping each unique element in the given
- * {@link Collection} to an {@link Integer} representing the number
- * of occurrences of that element in the {@link Collection}.
+ * Transforms all elements from input collection with the given transformer
+ * and adds them to the output collection.
* <p>
- * Only those elements present in the collection will appear as
- * keys in the map.
+ * If the input collection or transformer is null, there is no change to the
+ * output collection.
* </p>
*
- * @param <O> the type of object in the returned {@link Map}. This is a super type of <I>.
- * @param coll the collection to get the cardinality map for, must not be null
- * @return the populated cardinality map
- * @throws NullPointerException if coll is null
+ * @param <I> the type of object in the input collection
+ * @param <O> the type of object in the output collection
+ * @param <R> the type of the output collection
+ * @param inputCollection the collection to get the input from, may be null
+ * @param transformer the transformer to use, may be null
+ * @param outputCollection the collection to output into, may not be null if inputCollection
+ * and transformer are not null
+ * @return the output collection with the transformed input added
+ * @throws NullPointerException if the outputCollection is null and both, inputCollection and
+ * transformer are not null
*/
- public static <O> Map<O, Integer> getCardinalityMap(final Iterable<? extends O> coll) {
- Objects.requireNonNull(coll, "coll");
- final Map<O, Integer> count = new HashMap<>();
- for (final O obj : coll) {
- final Integer c = count.get(obj);
- if (c == null) {
- count.put(obj, Integer.valueOf(1));
- } else {
- count.put(obj, Integer.valueOf(c.intValue() + 1));
- }
+ public static <I, O, R extends Collection<? super O>> R collect(final Iterable<? extends I> inputCollection,
+ final Transformer<? super I, ? extends O> transformer, final R outputCollection) {
+ if (inputCollection != null) {
+ return collect(inputCollection.iterator(), transformer, outputCollection);
}
- return count;
+ return outputCollection;
}
/**
- * Returns {@code true} iff <i>a</i> is a sub-collection of <i>b</i>,
- * that is, iff the cardinality of <i>e</i> in <i>a</i> is less than or
- * equal to the cardinality of <i>e</i> in <i>b</i>, for each element <i>e</i>
- * in <i>a</i>.
+ * Returns a new Collection containing all elements of the input collection
+ * transformed by the given transformer.
+ * <p>
+ * If the input collection or transformer is null, the result is an empty list.
+ * </p>
*
- * @param a the first (sub?) collection, must not be null
- * @param b the second (super?) collection, must not be null
- * @return {@code true} iff <i>a</i> is a sub-collection of <i>b</i>
- * @throws NullPointerException if either collection is null
- * @see #isProperSubCollection
- * @see Collection#containsAll
+ * @param <I> the type of object in the input collection
+ * @param <O> the type of object in the output collection
+ * @param inputCollection the collection to get the input from, may not be null
+ * @param transformer the transformer to use, may be null
+ * @return the transformed result (new list)
+ * @throws NullPointerException if the outputCollection is null and both, inputCollection and
+ * transformer are not null
*/
- public static boolean isSubCollection(final Collection<?> a, final Collection<?> b) {
- Objects.requireNonNull(a, "a");
- Objects.requireNonNull(b, "b");
- final CardinalityHelper<Object> helper = new CardinalityHelper<>(a, b);
- for (final Object obj : a) {
- if (helper.freqA(obj) > helper.freqB(obj)) {
- return false;
- }
+ public static <I, O> Collection<O> collect(final Iterable<I> inputCollection,
+ final Transformer<? super I, ? extends O> transformer) {
+ int size = 0;
+ if (null != inputCollection) {
+ size = inputCollection instanceof Collection<?> ? ((Collection<?>) inputCollection).size() : 0;
}
- return true;
+ final Collection<O> answer = size == 0 ? new ArrayList<>() : new ArrayList<>(size);
+ return collect(inputCollection, transformer, answer);
}
/**
- * Returns {@code true} iff <i>a</i> is a <i>proper</i> sub-collection of <i>b</i>,
- * that is, iff the cardinality of <i>e</i> in <i>a</i> is less
- * than or equal to the cardinality of <i>e</i> in <i>b</i>,
- * for each element <i>e</i> in <i>a</i>, and there is at least one
- * element <i>f</i> such that the cardinality of <i>f</i> in <i>b</i>
- * is strictly greater than the cardinality of <i>f</i> in <i>a</i>.
+ * Transforms all elements from the input iterator with the given transformer
+ * and adds them to the output collection.
* <p>
- * The implementation assumes
+ * If the input iterator or transformer is null, there is no change to the
+ * output collection.
* </p>
- * <ul>
- * <li>{@code a.size()} and {@code b.size()} represent the
- * total cardinality of <i>a</i> and <i>b</i>, resp. </li>
- * <li>{@code a.size() < Integer.MAXVALUE}</li>
- * </ul>
*
- * @param a the first (sub?) collection, must not be null
- * @param b the second (super?) collection, must not be null
- * @return {@code true} iff <i>a</i> is a <i>proper</i> sub-collection of <i>b</i>
- * @throws NullPointerException if either collection is null
- * @see #isSubCollection
- * @see Collection#containsAll
+ * @param <I> the type of object in the input collection
+ * @param <O> the type of object in the output collection
+ * @param <R> the type of the output collection
+ * @param inputIterator the iterator to get the input from, may be null
+ * @param transformer the transformer to use, may be null
+ * @param outputCollection the collection to output into, may not be null if inputIterator
+ * and transformer are not null
+ * @return the outputCollection with the transformed input added
+ * @throws NullPointerException if the output collection is null and both, inputIterator and
+ * transformer are not null
*/
- public static boolean isProperSubCollection(final Collection<?> a, final Collection<?> b) {
- Objects.requireNonNull(a, "a");
- Objects.requireNonNull(b, "b");
- return a.size() < b.size() && CollectionUtils.isSubCollection(a, b);
+ public static <I, O, R extends Collection<? super O>> R collect(final Iterator<? extends I> inputIterator,
+ final Transformer<? super I, ? extends O> transformer, final R outputCollection) {
+ if (inputIterator != null && transformer != null) {
+ while (inputIterator.hasNext()) {
+ final I item = inputIterator.next();
+ final O value = transformer.transform(item);
+ outputCollection.add(value);
+ }
+ }
+ return outputCollection;
}
/**
- * Returns {@code true} iff the given {@link Collection}s contain
- * exactly the same elements with exactly the same cardinalities.
+ * Transforms all elements from the input iterator with the given transformer
+ * and adds them to the output collection.
* <p>
- * That is, iff the cardinality of <i>e</i> in <i>a</i> is
- * equal to the cardinality of <i>e</i> in <i>b</i>,
- * for each element <i>e</i> in <i>a</i> or <i>b</i>.
+ * If the input iterator or transformer is null, the result is an empty list.
* </p>
*
- * @param a the first collection, must not be null
- * @param b the second collection, must not be null
- * @return {@code true} iff the collections contain the same elements with the same cardinalities.
- * @throws NullPointerException if either collection is null
+ * @param <I> the type of object in the input collection
+ * @param <O> the type of object in the output collection
+ * @param inputIterator the iterator to get the input from, may be null
+ * @param transformer the transformer to use, may be null
+ * @return the transformed result (new list)
*/
- public static boolean isEqualCollection(final Collection<?> a, final Collection<?> b) {
- Objects.requireNonNull(a, "a");
- Objects.requireNonNull(b, "b");
- if (a.size() != b.size()) {
- return false;
- }
- final CardinalityHelper<Object> helper = new CardinalityHelper<>(a, b);
- if (helper.cardinalityA.size() != helper.cardinalityB.size()) {
- return false;
- }
- for (final Object obj : helper.cardinalityA.keySet()) {
- if (helper.freqA(obj) != helper.freqB(obj)) {
- return false;
- }
- }
- return true;
+ public static <I, O> Collection<O> collect(final Iterator<I> inputIterator,
+ final Transformer<? super I, ? extends O> transformer) {
+ return collect(inputIterator, transformer, new ArrayList<>());
}
/**
- * Returns {@code true} iff the given {@link Collection}s contain
- * exactly the same elements with exactly the same cardinalities.
+ * Returns {@code true} iff all elements of {@code coll2} are also contained
+ * in {@code coll1}. The cardinality of values in {@code coll2} is not taken into account,
+ * which is the same behavior as {@link Collection#containsAll(Collection)}.
* <p>
- * That is, iff the cardinality of <i>e</i> in <i>a</i> is
- * equal to the cardinality of <i>e</i> in <i>b</i>,
- * for each element <i>e</i> in <i>a</i> or <i>b</i>.
+ * In other words, this method returns {@code true} iff the
+ * {@link #intersection} of <i>coll1</i> and <i>coll2</i> has the same cardinality as
+ * the set of unique values from {@code coll2}. In case {@code coll2} is empty, {@code true}
+ * will be returned.
* </p>
* <p>
- * <b>Note:</b> from version 4.1 onwards this method requires the input
- * collections and equator to be of compatible type (using bounded wildcards).
- * Providing incompatible arguments (e.g. by casting to their rawtypes)
- * will result in a {@code ClassCastException} thrown at runtime.
+ * This method is intended as a replacement for {@link Collection#containsAll(Collection)}
+ * with a guaranteed runtime complexity of {@code O(n + m)}. Depending on the type of
+ * {@link Collection} provided, this method will be much faster than calling
+ * {@link Collection#containsAll(Collection)} instead, though this will come at the
+ * cost of an additional space complexity O(n).
* </p>
*
- * @param <E> the element type
- * @param a the first collection, must not be null
- * @param b the second collection, must not be null
- * @param equator the Equator used for testing equality
- * @return {@code true} iff the collections contain the same elements with the same cardinalities.
- * @throws NullPointerException if either collection or equator is null
+ * @param coll1 the first collection, must not be null
+ * @param coll2 the second collection, must not be null
+ * @return {@code true} iff the intersection of the collections has the same cardinality
+ * as the set of unique elements from the second collection
+ * @throws NullPointerException if coll1 or coll2 is null
* @since 4.0
*/
- public static <E> boolean isEqualCollection(final Collection<? extends E> a,
- final Collection<? extends E> b,
- final Equator<? super E> equator) {
- Objects.requireNonNull(a, "a");
- Objects.requireNonNull(b, "b");
- Objects.requireNonNull(equator, "equator");
-
- if (a.size() != b.size()) {
- return false;
+ public static boolean containsAll(final Collection<?> coll1, final Collection<?> coll2) {
+ Objects.requireNonNull(coll1, "coll1");
+ Objects.requireNonNull(coll2, "coll2");
+ if (coll2.isEmpty()) {
+ return true;
}
+ final Set<Object> elementsAlreadySeen = new HashSet<>();
+ for (final Object nextElement : coll2) {
+ if (elementsAlreadySeen.contains(nextElement)) {
+ continue;
+ }
- @SuppressWarnings({ "unchecked", "rawtypes" })
- final Transformer<E, ?> transformer = input -> new EquatorWrapper(equator, input);
-
- return isEqualCollection(collect(a, transformer), collect(b, transformer));
+ boolean foundCurrentElement = false;
+ for (final Object p : coll1) {
+ elementsAlreadySeen.add(p);
+ if (Objects.equals(nextElement, p)) {
+ foundCurrentElement = true;
+ break;
+ }
+ }
+
+ if (!foundCurrentElement) {
+ return false;
+ }
+ }
+ return true;
}
/**
- * Returns the hash code of the input collection using the hash method of an equator.
- *
+ * Returns {@code true} iff at least one element is in both collections.
* <p>
- * Returns 0 if the input collection is {@code null}.
+ * In other words, this method returns {@code true} iff the
+ * {@link #intersection} of <i>coll1</i> and <i>coll2</i> is not empty.
* </p>
*
- * @param <E> the element type
- * @param collection the input collection
- * @param equator the equator used for generate hashCode
- * @return the hash code of the input collection using the hash method of an equator
- * @throws NullPointerException if the equator is {@code null}
- * @since 4.5
+ * @param coll1 the first collection, must not be null
+ * @param coll2 the second collection, must not be null
+ * @return {@code true} iff the intersection of the collections is non-empty
+ * @throws NullPointerException if coll1 or coll2 is null
+ * @since 2.1
+ * @see #intersection
*/
- public static <E> int hashCode(final Collection<? extends E> collection,
- final Equator<? super E> equator) {
- Objects.requireNonNull(equator, "equator");
- if (null == collection) {
- return 0;
- }
- int hashCode = 1;
- for (final E e : collection) {
- hashCode = 31 * hashCode + equator.hash(e);
+ public static boolean containsAny(final Collection<?> coll1, final Collection<?> coll2) {
+ Objects.requireNonNull(coll1, "coll1");
+ Objects.requireNonNull(coll2, "coll2");
+ if (coll1.size() < coll2.size()) {
+ for (final Object aColl1 : coll1) {
+ if (coll2.contains(aColl1)) {
+ return true;
+ }
+ }
+ } else {
+ for (final Object aColl2 : coll2) {
+ if (coll1.contains(aColl2)) {
+ return true;
+ }
+ }
}
- return hashCode;
+ return false;
}
/**
- * Wraps another object and uses the provided Equator to implement
- * {@link #equals(Object)} and {@link #hashCode()}.
+ * Returns {@code true} iff at least one element is in both collections.
* <p>
- * This class can be used to store objects into a Map.
+ * In other words, this method returns {@code true} iff the
+ * {@link #intersection} of <i>coll1</i> and <i>coll2</i> is not empty.
* </p>
*
- * @param <O> the element type
- * @since 4.0
+ * @param <T> the type of object to lookup in {@code coll1}.
+ * @param coll1 the first collection, must not be null
+ * @param coll2 the second collection, must not be null
+ * @return {@code true} iff the intersection of the collections is non-empty
+ * @throws NullPointerException if coll1 or coll2 is null
+ * @since 4.2
+ * @see #intersection
*/
- private static final class EquatorWrapper<O> {
- private final Equator<? super O> equator;
- private final O object;
-
- EquatorWrapper(final Equator<? super O> equator, final O object) {
- this.equator = equator;
- this.object = object;
- }
-
- public O getObject() {
- return object;
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (!(obj instanceof EquatorWrapper)) {
- return false;
+ public static <T> boolean containsAny(final Collection<?> coll1, @SuppressWarnings("unchecked") final T... coll2) {
+ Objects.requireNonNull(coll1, "coll1");
+ Objects.requireNonNull(coll2, "coll2");
+ if (coll1.size() < coll2.length) {
+ for (final Object aColl1 : coll1) {
+ if (ArrayUtils.contains(coll2, aColl1)) {
+ return true;
+ }
+ }
+ } else {
+ for (final Object aColl2 : coll2) {
+ if (coll1.contains(aColl2)) {
+ return true;
+ }
}
- @SuppressWarnings("unchecked")
- final EquatorWrapper<O> otherObj = (EquatorWrapper<O>) obj;
- return equator.equate(object, otherObj.getObject());
- }
-
- @Override
- public int hashCode() {
- return equator.hash(object);
}
+ return false;
}
/**
- * Returns the number of occurrences of <i>obj</i> in <i>coll</i>.
- *
- * @param obj the object to find the cardinality of
- * @param collection the {@link Iterable} to search
- * @param <O> the type of object that the {@link Iterable} may contain.
- * @return the number of occurrences of obj in coll
- * @throws NullPointerException if collection is null
- * @deprecated since 4.1, use {@link IterableUtils#frequency(Iterable, Object)} instead.
- * Be aware that the order of parameters has changed.
- */
- @Deprecated
- public static <O> int cardinality(final O obj, final Iterable<? super O> collection) {
- return IterableUtils.frequency(Objects.requireNonNull(collection, "collection"), obj);
- }
-
- /**
- * Finds the first element in the given collection which matches the given predicate.
+ * Counts the number of elements in the input collection that match the
+ * predicate.
* <p>
- * If the input collection or predicate is null, or no element of the collection
- * matches the predicate, null is returned.
+ * A {@code null} collection or predicate matches no elements.
* </p>
*
- * @param <T> the type of object the {@link Iterable} contains
- * @param collection the collection to search, may be null
+ * @param <C> the type of object the {@link Iterable} contains
+ * @param input the {@link Iterable} to get the input from, may be null
* @param predicate the predicate to use, may be null
- * @return the first element of the collection which matches the predicate or null if none could be found
- * @deprecated since 4.1, use {@link IterableUtils#find(Iterable, Predicate)} instead
+ * @return the number of matches for the predicate in the collection
+ * @deprecated since 4.1, use {@link IterableUtils#countMatches(Iterable, Predicate)} instead
*/
@Deprecated
- public static <T> T find(final Iterable<T> collection, final Predicate<? super T> predicate) {
- return predicate != null ? IterableUtils.find(collection, predicate) : null;
+ public static <C> int countMatches(final Iterable<C> input, final Predicate<? super C> predicate) {
+ return predicate == null ? 0 : (int) IterableUtils.countMatches(input, predicate);
}
/**
- * Executes the given closure on each element in the collection.
+ * Returns a {@link Collection} containing the exclusive disjunction
+ * (symmetric difference) of the given {@link Iterable}s.
* <p>
- * If the input collection or closure is null, there is no change made.
+ * The cardinality of each element <i>e</i> in the returned
+ * {@link Collection} will be equal to
+ * <code>max(cardinality(<i>e</i>,<i>a</i>),cardinality(<i>e</i>,<i>b</i>)) - min(cardinality(<i>e</i>,<i>a</i>),
+ * cardinality(<i>e</i>,<i>b</i>))</code>.
+ * </p>
+ * <p>
+ * This is equivalent to
+ * {@code {@link #subtract subtract}({@link #union union(a,b)},{@link #intersection intersection(a,b)})}
+ * or
+ * {@code {@link #union union}({@link #subtract subtract(a,b)},{@link #subtract subtract(b,a)})}.
* </p>
*
- * @param <T> the type of object the {@link Iterable} contains
- * @param <C> the closure type
- * @param collection the collection to get the input from, may be null
- * @param closure the closure to perform, may be null
- * @return closure
- * @deprecated since 4.1, use {@link IterableUtils#forEach(Iterable, Closure)} instead
+ * @param a the first collection, must not be null
+ * @param b the second collection, must not be null
+ * @param <O> the generic type that is able to represent the types contained
+ * in both input collections.
+ * @return the symmetric difference of the two collections
+ * @throws NullPointerException if either collection is null
*/
- @Deprecated
- public static <T, C extends Closure<? super T>> C forAllDo(final Iterable<T> collection, final C closure) {
- if (closure != null) {
- IterableUtils.forEach(collection, closure);
+ public static <O> Collection<O> disjunction(final Iterable<? extends O> a, final Iterable<? extends O> b) {
+ Objects.requireNonNull(a, "a");
+ Objects.requireNonNull(b, "b");
+ final SetOperationCardinalityHelper<O> helper = new SetOperationCardinalityHelper<>(a, b);
+ for (final O obj : helper) {
+ helper.setCardinality(obj, helper.max(obj) - helper.min(obj));
}
- return closure;
+ return helper.list();
}
/**
- * Executes the given closure on each element in the collection.
- * <p>
- * If the input collection or closure is null, there is no change made.
- * </p>
+ * Returns the immutable EMPTY_COLLECTION with generic type safety.
*
- * @param <T> the type of object the {@link Iterator} contains
- * @param <C> the closure type
- * @param iterator the iterator to get the input from, may be null
- * @param closure the closure to perform, may be null
- * @return closure
+ * @see #EMPTY_COLLECTION
* @since 4.0
- * @deprecated since 4.1, use {@link IteratorUtils#forEach(Iterator, Closure)} instead
+ * @param <T> the element type
+ * @return immutable empty collection
*/
- @Deprecated
- public static <T, C extends Closure<? super T>> C forAllDo(final Iterator<T> iterator, final C closure) {
- if (closure != null) {
- IteratorUtils.forEach(iterator, closure);
- }
- return closure;
+ @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type
+ public static <T> Collection<T> emptyCollection() {
+ return EMPTY_COLLECTION;
}
/**
- * Executes the given closure on each but the last element in the collection.
- * <p>
- * If the input collection or closure is null, there is no change made.
- * </p>
+ * Returns an immutable empty collection if the argument is {@code null},
+ * or the argument itself otherwise.
*
- * @param <T> the type of object the {@link Iterable} contains
- * @param <C> the closure type
- * @param collection the collection to get the input from, may be null
- * @param closure the closure to perform, may be null
- * @return the last element in the collection, or null if either collection or closure is null
- * @since 4.0
- * @deprecated since 4.1, use {@link IterableUtils#forEachButLast(Iterable, Closure)} instead
+ * @param <T> the element type
+ * @param collection the collection, possibly {@code null}
+ * @return an empty collection if the argument is {@code null}
*/
- @Deprecated
- public static <T, C extends Closure<? super T>> T forAllButLastDo(final Iterable<T> collection,
- final C closure) {
- return closure != null ? IterableUtils.forEachButLast(collection, closure) : null;
+ public static <T> Collection<T> emptyIfNull(final Collection<T> collection) {
+ return collection == null ? CollectionUtils.<T>emptyCollection() : collection;
}
/**
- * Executes the given closure on each but the last element in the collection.
+ * Answers true if a predicate is true for at least one element of a
+ * collection.
* <p>
- * If the input collection or closure is null, there is no change made.
+ * A {@code null} collection or predicate returns false.
* </p>
*
- * @param <T> the type of object the {@link Collection} contains
- * @param <C> the closure type
- * @param iterator the iterator to get the input from, may be null
- * @param closure the closure to perform, may be null
- * @return the last element in the collection, or null if either iterator or closure is null
- * @since 4.0
- * @deprecated since 4.1, use {@link IteratorUtils#forEachButLast(Iterator, Closure)} instead
+ * @param <C> the type of object the {@link Iterable} contains
+ * @param input the {@link Iterable} to get the input from, may be null
+ * @param predicate the predicate to use, may be null
+ * @return true if at least one element of the collection matches the predicate
+ * @deprecated since 4.1, use {@link IterableUtils#matchesAny(Iterable, Predicate)} instead
*/
@Deprecated
- public static <T, C extends Closure<? super T>> T forAllButLastDo(final Iterator<T> iterator, final C closure) {
- return closure != null ? IteratorUtils.forEachButLast(iterator, closure) : null;
+ public static <C> boolean exists(final Iterable<C> input, final Predicate<? super C> predicate) {
+ return predicate != null && IterableUtils.matchesAny(input, predicate);
+ }
+
+ /**
+ * Extract the lone element of the specified Collection.
+ *
+ * @param <E> collection type
+ * @param collection to read
+ * @return sole member of collection
+ * @throws NullPointerException if collection is null
+ * @throws IllegalArgumentException if collection is empty or contains more than one element
+ * @since 4.0
+ */
+ public static <E> E extractSingleton(final Collection<E> collection) {
+ Objects.requireNonNull(collection, "collection");
+ if (collection.size() != 1) {
+ throw new IllegalArgumentException("Can extract singleton only when collection size == 1");
+ }
+ return collection.iterator().next();
}
/**
@@ -903,706 +863,818 @@ public class CollectionUtils {
}
/**
- * Transform the collection by applying a Transformer to each element.
- * <p>
- * If the input collection or transformer is null, there is no change made.
- * </p>
- * <p>
- * This routine is best for Lists, for which set() is used to do the
- * transformations "in place." For other Collections, clear() and addAll()
- * are used to replace elements.
- * </p>
- * <p>
- * If the input collection controls its input, such as a Set, and the
- * Transformer creates duplicates (or are otherwise invalid), the collection
- * may reduce in size due to calling this method.
- * </p>
- *
- * @param <C> the type of object the {@link Collection} contains
- * @param collection the {@link Collection} to get the input from, may be null
- * @param transformer the transformer to perform, may be null
- */
- public static <C> void transform(final Collection<C> collection,
- final Transformer<? super C, ? extends C> transformer) {
-
- if (collection != null && transformer != null) {
- if (collection instanceof List<?>) {
- final List<C> list = (List<C>) collection;
- for (final ListIterator<C> it = list.listIterator(); it.hasNext();) {
- it.set(transformer.transform(it.next()));
- }
- } else {
- final Collection<C> resultCollection = collect(collection, transformer);
- collection.clear();
- collection.addAll(resultCollection);
- }
- }
- }
-
- /**
- * Counts the number of elements in the input collection that match the
- * predicate.
+ * Finds the first element in the given collection which matches the given predicate.
* <p>
- * A {@code null} collection or predicate matches no elements.
+ * If the input collection or predicate is null, or no element of the collection
+ * matches the predicate, null is returned.
* </p>
*
- * @param <C> the type of object the {@link Iterable} contains
- * @param input the {@link Iterable} to get the input from, may be null
+ * @param <T> the type of object the {@link Iterable} contains
+ * @param collection the collection to search, may be null
* @param predicate the predicate to use, may be null
- * @return the number of matches for the predicate in the collection
- * @deprecated since 4.1, use {@link IterableUtils#countMatches(Iterable, Predicate)} instead
+ * @return the first element of the collection which matches the predicate or null if none could be found
+ * @deprecated since 4.1, use {@link IterableUtils#find(Iterable, Predicate)} instead
*/
@Deprecated
- public static <C> int countMatches(final Iterable<C> input, final Predicate<? super C> predicate) {
- return predicate == null ? 0 : (int) IterableUtils.countMatches(input, predicate);
+ public static <T> T find(final Iterable<T> collection, final Predicate<? super T> predicate) {
+ return predicate != null ? IterableUtils.find(collection, predicate) : null;
}
/**
- * Answers true if a predicate is true for at least one element of a
- * collection.
+ * Executes the given closure on each but the last element in the collection.
* <p>
- * A {@code null} collection or predicate returns false.
+ * If the input collection or closure is null, there is no change made.
* </p>
*
- * @param <C> the type of object the {@link Iterable} contains
- * @param input the {@link Iterable} to get the input from, may be null
- * @param predicate the predicate to use, may be null
- * @return true if at least one element of the collection matches the predicate
- * @deprecated since 4.1, use {@link IterableUtils#matchesAny(Iterable, Predicate)} instead
+ * @param <T> the type of object the {@link Iterable} contains
+ * @param <C> the closure type
+ * @param collection the collection to get the input from, may be null
+ * @param closure the closure to perform, may be null
+ * @return the last element in the collection, or null if either collection or closure is null
+ * @since 4.0
+ * @deprecated since 4.1, use {@link IterableUtils#forEachButLast(Iterable, Closure)} instead
*/
@Deprecated
- public static <C> boolean exists(final Iterable<C> input, final Predicate<? super C> predicate) {
- return predicate != null && IterableUtils.matchesAny(input, predicate);
+ public static <T, C extends Closure<? super T>> T forAllButLastDo(final Iterable<T> collection,
+ final C closure) {
+ return closure != null ? IterableUtils.forEachButLast(collection, closure) : null;
}
/**
- * Answers true if a predicate is true for every element of a
- * collection.
- *
- * <p>
- * A {@code null} predicate returns false.
- * </p>
+ * Executes the given closure on each but the last element in the collection.
* <p>
- * A {@code null} or empty collection returns true.
+ * If the input collection or closure is null, there is no change made.
* </p>
*
- * @param <C> the type of object the {@link Iterable} contains
- * @param input the {@link Iterable} to get the input from, may be null
- * @param predicate the predicate to use, may be null
- * @return true if every element of the collection matches the predicate or if the
- * collection is empty, false otherwise
+ * @param <T> the type of object the {@link Collection} contains
+ * @param <C> the closure type
+ * @param iterator the iterator to get the input from, may be null
+ * @param closure the closure to perform, may be null
+ * @return the last element in the collection, or null if either iterator or closure is null
* @since 4.0
- * @deprecated since 4.1, use {@link IterableUtils#matchesAll(Iterable, Predicate)} instead
+ * @deprecated since 4.1, use {@link IteratorUtils#forEachButLast(Iterator, Closure)} instead
*/
@Deprecated
- public static <C> boolean matchesAll(final Iterable<C> input, final Predicate<? super C> predicate) {
- return predicate != null && IterableUtils.matchesAll(input, predicate);
+ public static <T, C extends Closure<? super T>> T forAllButLastDo(final Iterator<T> iterator, final C closure) {
+ return closure != null ? IteratorUtils.forEachButLast(iterator, closure) : null;
}
/**
- * Selects all elements from input collection which match the given
- * predicate into an output collection.
+ * Executes the given closure on each element in the collection.
* <p>
- * A {@code null} predicate matches no elements.
+ * If the input collection or closure is null, there is no change made.
* </p>
*
- * @param <O> the type of object the {@link Iterable} contains
- * @param inputCollection the collection to get the input from, may not be null
- * @param predicate the predicate to use, may be null
- * @return the elements matching the predicate (new list)
+ * @param <T> the type of object the {@link Iterable} contains
+ * @param <C> the closure type
+ * @param collection the collection to get the input from, may be null
+ * @param closure the closure to perform, may be null
+ * @return closure
+ * @deprecated since 4.1, use {@link IterableUtils#forEach(Iterable, Closure)} instead
*/
- public static <O> Collection<O> select(final Iterable<? extends O> inputCollection,
- final Predicate<? super O> predicate) {
- int size = 0;
- if (null != inputCollection) {
- size = inputCollection instanceof Collection<?> ? ((Collection<?>) inputCollection).size() : 0;
+ @Deprecated
+ public static <T, C extends Closure<? super T>> C forAllDo(final Iterable<T> collection, final C closure) {
+ if (closure != null) {
+ IterableUtils.forEach(collection, closure);
}
- final Collection<O> answer = size == 0 ? new ArrayList<>() : new ArrayList<>(size);
- return select(inputCollection, predicate, answer);
+ return closure;
}
/**
- * Selects all elements from input collection which match the given
- * predicate and adds them to outputCollection.
+ * Executes the given closure on each element in the collection.
* <p>
- * If the input collection or predicate is null, there is no change to the
- * output collection.
+ * If the input collection or closure is null, there is no change made.
* </p>
*
- * @param <O> the type of object the {@link Iterable} contains
- * @param <R> the type of the output {@link Collection}
- * @param inputCollection the collection to get the input from, may be null
- * @param predicate the predicate to use, may be null
- * @param outputCollection the collection to output into, may not be null if the inputCollection
- * and predicate or not null
- * @return the outputCollection
+ * @param <T> the type of object the {@link Iterator} contains
+ * @param <C> the closure type
+ * @param iterator the iterator to get the input from, may be null
+ * @param closure the closure to perform, may be null
+ * @return closure
+ * @since 4.0
+ * @deprecated since 4.1, use {@link IteratorUtils#forEach(Iterator, Closure)} instead
*/
- public static <O, R extends Collection<? super O>> R select(final Iterable<? extends O> inputCollection,
- final Predicate<? super O> predicate, final R outputCollection) {
-
- if (inputCollection != null && predicate != null) {
- for (final O item : inputCollection) {
- if (predicate.evaluate(item)) {
- outputCollection.add(item);
- }
- }
+ @Deprecated
+ public static <T, C extends Closure<? super T>> C forAllDo(final Iterator<T> iterator, final C closure) {
+ if (closure != null) {
+ IteratorUtils.forEach(iterator, closure);
}
- return outputCollection;
+ return closure;
}
/**
- * Selects all elements from inputCollection into an output and rejected collection,
- * based on the evaluation of the given predicate.
- * <p>
- * Elements matching the predicate are added to the {@code outputCollection},
- * all other elements are added to the {@code rejectedCollection}.
- * </p>
- * <p>
- * If the input predicate is {@code null}, no elements are added to
- * {@code outputCollection} or {@code rejectedCollection}.
- * </p>
+ * Returns the {@code index}-th value in the {@code iterable}'s {@link Iterator}, throwing
+ * {@code IndexOutOfBoundsException} if there is no such element.
* <p>
- * Note: calling the method is equivalent to the following code snippet:
+ * If the {@link Iterable} is a {@link List}, then it will use {@link List#get(int)}.
* </p>
- * <pre>
- * select(inputCollection, predicate, outputCollection);
- * selectRejected(inputCollection, predicate, rejectedCollection);
- * </pre>
*
- * @param <O> the type of object the {@link Iterable} contains
- * @param <R> the type of the output {@link Collection}
- * @param inputCollection the collection to get the input from, may be null
- * @param predicate the predicate to use, may be null
- * @param outputCollection the collection to output selected elements into, may not be null if the
- * inputCollection and predicate are not null
- * @param rejectedCollection the collection to output rejected elements into, may not be null if the
- * inputCollection or predicate are not null
- * @return the outputCollection
- * @since 4.1
+ * @param iterable the {@link Iterable} to get a value from
+ * @param index the index to get
+ * @param <T> the type of object in the {@link Iterable}.
+ * @return the object at the specified index
+ * @throws IndexOutOfBoundsException if the index is invalid
+ * @deprecated since 4.1, use {@code IterableUtils.get(Iterable, int)} instead
*/
- public static <O, R extends Collection<? super O>> R select(final Iterable<? extends O> inputCollection,
- final Predicate<? super O> predicate, final R outputCollection, final R rejectedCollection) {
-
- if (inputCollection != null && predicate != null) {
- for (final O element : inputCollection) {
- if (predicate.evaluate(element)) {
- outputCollection.add(element);
- } else {
- rejectedCollection.add(element);
- }
- }
- }
- return outputCollection;
+ @Deprecated
+ public static <T> T get(final Iterable<T> iterable, final int index) {
+ Objects.requireNonNull(iterable, "iterable");
+ return IterableUtils.get(iterable, index);
}
/**
- * Selects all elements from inputCollection which don't match the given
- * predicate into an output collection.
+ * Returns the {@code index}-th value in {@link Iterator}, throwing
+ * {@code IndexOutOfBoundsException} if there is no such element.
* <p>
- * If the input predicate is {@code null}, the result is an empty
- * list.
+ * The Iterator is advanced to {@code index} (or to the end, if
+ * {@code index} exceeds the number of entries) as a side effect of this method.
* </p>
*
- * @param <O> the type of object the {@link Iterable} contains
- * @param inputCollection the collection to get the input from, may not be null
- * @param predicate the predicate to use, may be null
- * @return the elements <b>not</b> matching the predicate (new list)
+ * @param iterator the iterator to get a value from
+ * @param index the index to get
+ * @param <T> the type of object in the {@link Iterator}
+ * @return the object at the specified index
+ * @throws IndexOutOfBoundsException if the index is invalid
+ * @throws IllegalArgumentException if the object type is invalid
+ * @throws NullPointerException if iterator is null
+ * @deprecated since 4.1, use {@code IteratorUtils.get(Iterator, int)} instead
*/
- public static <O> Collection<O> selectRejected(final Iterable<? extends O> inputCollection,
- final Predicate<? super O> predicate) {
- int size = 0;
- if (null != inputCollection) {
- size = inputCollection instanceof Collection<?> ? ((Collection<?>) inputCollection).size() : 0;
- }
- final Collection<O> answer = size == 0 ? new ArrayList<>() : new ArrayList<>(size);
- return selectRejected(inputCollection, predicate, answer);
+ @Deprecated
+ public static <T> T get(final Iterator<T> iterator, final int index) {
+ Objects.requireNonNull(iterator, "iterator");
+ return IteratorUtils.get(iterator, index);
}
/**
- * Selects all elements from inputCollection which don't match the given
- * predicate and adds them to outputCollection.
- * <p>
- * If the input predicate is {@code null}, no elements are added to
- * {@code outputCollection}.
- * </p>
+ * Returns the {@code index}-th {@code Map.Entry} in the {@code map}'s {@code entrySet},
+ * throwing {@code IndexOutOfBoundsException} if there is no such element.
*
- * @param <O> the type of object the {@link Iterable} contains
- * @param <R> the type of the output {@link Collection}
- * @param inputCollection the collection to get the input from, may be null
- * @param predicate the predicate to use, may be null
- * @param outputCollection the collection to output into, may not be null if the inputCollection
- * and predicate or not null
- * @return outputCollection
+ * @param <K> the key type in the {@link Map}
+ * @param <V> the value type in the {@link Map}
+ * @param map the object to get a value from
+ * @param index the index to get
+ * @return the object at the specified index
+ * @throws IndexOutOfBoundsException if the index is invalid
*/
- public static <O, R extends Collection<? super O>> R selectRejected(final Iterable<? extends O> inputCollection,
- final Predicate<? super O> predicate, final R outputCollection) {
-
- if (inputCollection != null && predicate != null) {
- for (final O item : inputCollection) {
- if (!predicate.evaluate(item)) {
- outputCollection.add(item);
- }
- }
- }
- return outputCollection;
+ public static <K, V> Map.Entry<K, V> get(final Map<K, V> map, final int index) {
+ Objects.requireNonNull(map, "map");
+ checkIndexBounds(index);
+ return get(map.entrySet(), index);
}
/**
- * Returns a new Collection containing all elements of the input collection
- * transformed by the given transformer.
+ * Returns the {@code index}-th value in {@code object}, throwing
+ * {@code IndexOutOfBoundsException} if there is no such element or
+ * {@code IllegalArgumentException} if {@code object} is not an
+ * instance of one of the supported types.
* <p>
- * If the input collection or transformer is null, the result is an empty list.
+ * The supported types, and associated semantics are:
* </p>
+ * <ul>
+ * <li> Map -- the value returned is the {@code Map.Entry} in position
+ * {@code index} in the map's {@code entrySet} iterator,
+ * if there is such an entry.</li>
+ * <li> List -- this method is equivalent to the list's get method.</li>
+ * <li> Array -- the {@code index}-th array entry is returned,
+ * if there is such an entry; otherwise an {@code IndexOutOfBoundsException}
+ * is thrown.</li>
+ * <li> Collection -- the value returned is the {@code index}-th object
+ * returned by the collection's default iterator, if there is such an element.</li>
+ * <li> Iterator or Enumeration -- the value returned is the
+ * {@code index}-th object in the Iterator/Enumeration, if there
+ * is such an element. The Iterator/Enumeration is advanced to
+ * {@code index} (or to the end, if {@code index} exceeds the
+ * number of entries) as a side effect of this method.</li>
+ * </ul>
*
- * @param <I> the type of object in the input collection
- * @param <O> the type of object in the output collection
- * @param inputCollection the collection to get the input from, may not be null
- * @param transformer the transformer to use, may be null
- * @return the transformed result (new list)
- * @throws NullPointerException if the outputCollection is null and both, inputCollection and
- * transformer are not null
+ * @param object the object to get a value from
+ * @param index the index to get
+ * @return the object at the specified index
+ * @throws IndexOutOfBoundsException if the index is invalid
+ * @throws IllegalArgumentException if the object type is invalid
*/
- public static <I, O> Collection<O> collect(final Iterable<I> inputCollection,
- final Transformer<? super I, ? extends O> transformer) {
- int size = 0;
- if (null != inputCollection) {
- size = inputCollection instanceof Collection<?> ? ((Collection<?>) inputCollection).size() : 0;
+ public static Object get(final Object object, final int index) {
+ final int i = index;
+ if (i < 0) {
+ throw new IndexOutOfBoundsException("Index cannot be negative: " + i);
+ }
+ if (object instanceof Map<?, ?>) {
+ final Map<?, ?> map = (Map<?, ?>) object;
+ final Iterator<?> iterator = map.entrySet().iterator();
+ return IteratorUtils.get(iterator, i);
+ }
+ if (object instanceof Object[]) {
+ return ((Object[]) object)[i];
+ }
+ if (object instanceof Iterator<?>) {
+ final Iterator<?> it = (Iterator<?>) object;
+ return IteratorUtils.get(it, i);
+ }
+ if (object instanceof Iterable<?>) {
+ final Iterable<?> iterable = (Iterable<?>) object;
+ return IterableUtils.get(iterable, i);
+ }
+ if (object instanceof Enumeration<?>) {
+ final Enumeration<?> it = (Enumeration<?>) object;
+ return EnumerationUtils.get(it, i);
+ }
+ if (object == null) {
+ throw new IllegalArgumentException("Unsupported object type: null");
+ }
+ try {
+ return Array.get(object, i);
+ } catch (final IllegalArgumentException ex) {
+ throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName());
}
- final Collection<O> answer = size == 0 ? new ArrayList<>() : new ArrayList<>(size);
- return collect(inputCollection, transformer, answer);
}
/**
- * Transforms all elements from the input iterator with the given transformer
- * and adds them to the output collection.
+ * Returns a {@link Map} mapping each unique element in the given
+ * {@link Collection} to an {@link Integer} representing the number
+ * of occurrences of that element in the {@link Collection}.
* <p>
- * If the input iterator or transformer is null, the result is an empty list.
+ * Only those elements present in the collection will appear as
+ * keys in the map.
* </p>
*
- * @param <I> the type of object in the input collection
- * @param <O> the type of object in the output collection
- * @param inputIterator the iterator to get the input from, may be null
- * @param transformer the transformer to use, may be null
- * @return the transformed result (new list)
+ * @param <O> the type of object in the returned {@link Map}. This is a super type of <I>.
+ * @param coll the collection to get the cardinality map for, must not be null
+ * @return the populated cardinality map
+ * @throws NullPointerException if coll is null
*/
- public static <I, O> Collection<O> collect(final Iterator<I> inputIterator,
- final Transformer<? super I, ? extends O> transformer) {
- return collect(inputIterator, transformer, new ArrayList<>());
+ public static <O> Map<O, Integer> getCardinalityMap(final Iterable<? extends O> coll) {
+ Objects.requireNonNull(coll, "coll");
+ final Map<O, Integer> count = new HashMap<>();
+ for (final O obj : coll) {
+ final Integer c = count.get(obj);
+ if (c == null) {
+ count.put(obj, Integer.valueOf(1));
+ } else {
+ count.put(obj, Integer.valueOf(c.intValue() + 1));
+ }
+ }
+ return count;
}
/**
- * Transforms all elements from input collection with the given transformer
- * and adds them to the output collection.
+ * Returns the hash code of the input collection using the hash method of an equator.
+ *
* <p>
- * If the input collection or transformer is null, there is no change to the
- * output collection.
+ * Returns 0 if the input collection is {@code null}.
* </p>
*
- * @param <I> the type of object in the input collection
- * @param <O> the type of object in the output collection
- * @param <R> the type of the output collection
- * @param inputCollection the collection to get the input from, may be null
- * @param transformer the transformer to use, may be null
- * @param outputCollection the collection to output into, may not be null if inputCollection
- * and transformer are not null
- * @return the output collection with the transformed input added
- * @throws NullPointerException if the outputCollection is null and both, inputCollection and
- * transformer are not null
+ * @param <E> the element type
+ * @param collection the input collection
+ * @param equator the equator used for generate hashCode
+ * @return the hash code of the input collection using the hash method of an equator
+ * @throws NullPointerException if the equator is {@code null}
+ * @since 4.5
*/
- public static <I, O, R extends Collection<? super O>> R collect(final Iterable<? extends I> inputCollection,
- final Transformer<? super I, ? extends O> transformer, final R outputCollection) {
- if (inputCollection != null) {
- return collect(inputCollection.iterator(), transformer, outputCollection);
+ public static <E> int hashCode(final Collection<? extends E> collection,
+ final Equator<? super E> equator) {
+ Objects.requireNonNull(equator, "equator");
+ if (null == collection) {
+ return 0;
}
- return outputCollection;
+ int hashCode = 1;
+ for (final E e : collection) {
+ hashCode = 31 * hashCode + equator.hash(e);
+ }
+ return hashCode;
}
/**
- * Transforms all elements from the input iterator with the given transformer
- * and adds them to the output collection.
+ * Returns a {@link Collection} containing the intersection of the given
+ * {@link Iterable}s.
* <p>
- * If the input iterator or transformer is null, there is no change to the
- * output collection.
+ * The cardinality of each element in the returned {@link Collection} will
+ * be equal to the minimum of the cardinality of that element in the two
+ * given {@link Iterable}s.
* </p>
*
- * @param <I> the type of object in the input collection
- * @param <O> the type of object in the output collection
- * @param <R> the type of the output collection
- * @param inputIterator the iterator to get the input from, may be null
- * @param transformer the transformer to use, may be null
- * @param outputCollection the collection to output into, may not be null if inputIterator
- * and transformer are not null
- * @return the outputCollection with the transformed input added
- * @throws NullPointerException if the output collection is null and both, inputIterator and
- * transformer are not null
+ * @param a the first collection, must not be null
+ * @param b the second collection, must not be null
+ * @param <O> the generic type that is able to represent the types contained
+ * in both input collections.
+ * @return the intersection of the two collections
+ * @throws NullPointerException if either collection is null
+ * @see Collection#retainAll
+ * @see #containsAny
*/
- public static <I, O, R extends Collection<? super O>> R collect(final Iterator<? extends I> inputIterator,
- final Transformer<? super I, ? extends O> transformer, final R outputCollection) {
- if (inputIterator != null && transformer != null) {
- while (inputIterator.hasNext()) {
- final I item = inputIterator.next();
- final O value = transformer.transform(item);
- outputCollection.add(value);
- }
+ public static <O> Collection<O> intersection(final Iterable<? extends O> a, final Iterable<? extends O> b) {
+ Objects.requireNonNull(a, "a");
+ Objects.requireNonNull(b, "b");
+ final SetOperationCardinalityHelper<O> helper = new SetOperationCardinalityHelper<>(a, b);
+ for (final O obj : helper) {
+ helper.setCardinality(obj, helper.min(obj));
}
- return outputCollection;
+ return helper.list();
}
/**
- * Adds an element to the collection unless the element is null.
+ * Null-safe check if the specified collection is empty.
+ * <p>
+ * Null returns true.
+ * </p>
*
- * @param <T> the type of object the {@link Collection} contains
- * @param collection the collection to add to, must not be null
- * @param object the object to add, if null it will not be added
- * @return true if the collection changed
- * @throws NullPointerException if the collection is null
+ * @param coll the collection to check, may be null
+ * @return true if empty or null
* @since 3.2
*/
- public static <T> boolean addIgnoreNull(final Collection<T> collection, final T object) {
- Objects.requireNonNull(collection, "collection");
- return object != null && collection.add(object);
+ public static boolean isEmpty(final Collection<?> coll) {
+ return coll == null || coll.isEmpty();
}
/**
- * Adds all elements in the {@link Iterable} to the given collection. If the
- * {@link Iterable} is a {@link Collection} then it is cast and will be
- * added using {@link Collection#addAll(Collection)} instead of iterating.
- *
- * @param <C> the type of object the {@link Collection} contains
- * @param collection the collection to add to, must not be null
- * @param iterable the iterable of elements to add, must not be null
- * @return a boolean indicating whether the collection has changed or not.
- * @throws NullPointerException if the collection or iterable is null
+ * Returns {@code true} iff the given {@link Collection}s contain
+ * exactly the same elements with exactly the same cardinalities.
+ * <p>
+ * That is, iff the cardinality of <i>e</i> in <i>a</i> is
+ * equal to the cardinality of <i>e</i> in <i>b</i>,
+ * for each element <i>e</i> in <i>a</i> or <i>b</i>.
+ * </p>
+ *
+ * @param a the first collection, must not be null
+ * @param b the second collection, must not be null
+ * @return {@code true} iff the collections contain the same elements with the same cardinalities.
+ * @throws NullPointerException if either collection is null
*/
- public static <C> boolean addAll(final Collection<C> collection, final Iterable<? extends C> iterable) {
- Objects.requireNonNull(collection, "collection");
- Objects.requireNonNull(iterable, "iterable");
- if (iterable instanceof Collection<?>) {
- return collection.addAll((Collection<? extends C>) iterable);
+ public static boolean isEqualCollection(final Collection<?> a, final Collection<?> b) {
+ Objects.requireNonNull(a, "a");
+ Objects.requireNonNull(b, "b");
+ if (a.size() != b.size()) {
+ return false;
}
- return addAll(collection, iterable.iterator());
+ final CardinalityHelper<Object> helper = new CardinalityHelper<>(a, b);
+ if (helper.cardinalityA.size() != helper.cardinalityB.size()) {
+ return false;
+ }
+ for (final Object obj : helper.cardinalityA.keySet()) {
+ if (helper.freqA(obj) != helper.freqB(obj)) {
+ return false;
+ }
+ }
+ return true;
}
/**
- * Adds all elements in the iteration to the given collection.
+ * Returns {@code true} iff the given {@link Collection}s contain
+ * exactly the same elements with exactly the same cardinalities.
+ * <p>
+ * That is, iff the cardinality of <i>e</i> in <i>a</i> is
+ * equal to the cardinality of <i>e</i> in <i>b</i>,
+ * for each element <i>e</i> in <i>a</i> or <i>b</i>.
+ * </p>
+ * <p>
+ * <b>Note:</b> from version 4.1 onwards this method requires the input
+ * collections and equator to be of compatible type (using bounded wildcards).
+ * Providing incompatible arguments (e.g. by casting to their rawtypes)
+ * will result in a {@code ClassCastException} thrown at runtime.
+ * </p>
*
- * @param <C> the type of object the {@link Collection} contains
- * @param collection the collection to add to, must not be null
- * @param iterator the iterator of elements to add, must not be null
- * @return a boolean indicating whether the collection has changed or not.
- * @throws NullPointerException if the collection or iterator is null
+ * @param <E> the element type
+ * @param a the first collection, must not be null
+ * @param b the second collection, must not be null
+ * @param equator the Equator used for testing equality
+ * @return {@code true} iff the collections contain the same elements with the same cardinalities.
+ * @throws NullPointerException if either collection or equator is null
+ * @since 4.0
*/
- public static <C> boolean addAll(final Collection<C> collection, final Iterator<? extends C> iterator) {
- Objects.requireNonNull(collection, "collection");
- Objects.requireNonNull(iterator, "iterator");
- boolean changed = false;
- while (iterator.hasNext()) {
- changed |= collection.add(iterator.next());
+ public static <E> boolean isEqualCollection(final Collection<? extends E> a,
+ final Collection<? extends E> b,
+ final Equator<? super E> equator) {
+ Objects.requireNonNull(a, "a");
+ Objects.requireNonNull(b, "b");
+ Objects.requireNonNull(equator, "equator");
+
+ if (a.size() != b.size()) {
+ return false;
}
- return changed;
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ final Transformer<E, ?> transformer = input -> new EquatorWrapper(equator, input);
+
+ return isEqualCollection(collect(a, transformer), collect(b, transformer));
}
/**
- * Adds all elements in the enumeration to the given collection.
+ * Returns true if no more elements can be added to the Collection.
+ * <p>
+ * This method uses the {@link BoundedCollection} interface to determine the
+ * full status. If the collection does not implement this interface then
+ * false is returned.
+ * </p>
+ * <p>
+ * The collection does not have to implement this interface directly.
+ * If the collection has been decorated using the decorators subpackage
+ * then these will be removed to access the BoundedCollection.
+ * </p>
*
- * @param <C> the type of object the {@link Collection} contains
- * @param collection the collection to add to, must not be null
- * @param enumeration the enumeration of elements to add, must not be null
- * @return {@code true} if the collections was changed, {@code false} otherwise
- * @throws NullPointerException if the collection or enumeration is null
+ * @param collection the collection to check
+ * @return true if the BoundedCollection is full
+ * @throws NullPointerException if the collection is null
*/
- public static <C> boolean addAll(final Collection<C> collection, final Enumeration<? extends C> enumeration) {
+ public static boolean isFull(final Collection<? extends Object> collection) {
Objects.requireNonNull(collection, "collection");
- Objects.requireNonNull(enumeration, "enumeration");
- boolean changed = false;
- while (enumeration.hasMoreElements()) {
- changed |= collection.add(enumeration.nextElement());
+ if (collection instanceof BoundedCollection) {
+ return ((BoundedCollection<?>) collection).isFull();
+ }
+ try {
+ final BoundedCollection<?> bcoll =
+ UnmodifiableBoundedCollection.unmodifiableBoundedCollection(collection);
+ return bcoll.isFull();
+ } catch (final IllegalArgumentException ex) {
+ return false;
}
- return changed;
}
/**
- * Adds all elements in the array to the given collection.
+ * Null-safe check if the specified collection is not empty.
+ * <p>
+ * Null returns false.
+ * </p>
*
- * @param <C> the type of object the {@link Collection} contains
- * @param collection the collection to add to, must not be null
- * @param elements the array of elements to add, must not be null
- * @return {@code true} if the collection was changed, {@code false} otherwise
- * @throws NullPointerException if the collection or elements is null
+ * @param coll the collection to check, may be null
+ * @return true if non-null and non-empty
+ * @since 3.2
*/
- public static <C> boolean addAll(final Collection<C> collection, final C... elements) {
- Objects.requireNonNull(collection, "collection");
- Objects.requireNonNull(elements, "elements");
- boolean changed = false;
- for (final C element : elements) {
- changed |= collection.add(element);
- }
- return changed;
+ public static boolean isNotEmpty(final Collection<?> coll) {
+ return !isEmpty(coll);
}
/**
- * Returns the {@code index}-th value in {@link Iterator}, throwing
- * {@code IndexOutOfBoundsException} if there is no such element.
+ * Returns {@code true} iff <i>a</i> is a <i>proper</i> sub-collection of <i>b</i>,
+ * that is, iff the cardinality of <i>e</i> in <i>a</i> is less
+ * than or equal to the cardinality of <i>e</i> in <i>b</i>,
+ * for each element <i>e</i> in <i>a</i>, and there is at least one
+ * element <i>f</i> such that the cardinality of <i>f</i> in <i>b</i>
+ * is strictly greater than the cardinality of <i>f</i> in <i>a</i>.
* <p>
- * The Iterator is advanced to {@code index} (or to the end, if
- * {@code index} exceeds the number of entries) as a side effect of this method.
+ * The implementation assumes
* </p>
+ * <ul>
+ * <li>{@code a.size()} and {@code b.size()} represent the
+ * total cardinality of <i>a</i> and <i>b</i>, resp. </li>
+ * <li>{@code a.size() < Integer.MAXVALUE}</li>
+ * </ul>
*
- * @param iterator the iterator to get a value from
- * @param index the index to get
- * @param <T> the type of object in the {@link Iterator}
- * @return the object at the specified index
- * @throws IndexOutOfBoundsException if the index is invalid
- * @throws IllegalArgumentException if the object type is invalid
- * @throws NullPointerException if iterator is null
- * @deprecated since 4.1, use {@code IteratorUtils.get(Iterator, int)} instead
+ * @param a the first (sub?) collection, must not be null
+ * @param b the second (super?) collection, must not be null
+ * @return {@code true} iff <i>a</i> is a <i>proper</i> sub-collection of <i>b</i>
+ * @throws NullPointerException if either collection is null
+ * @see #isSubCollection
+ * @see Collection#containsAll
*/
- @Deprecated
- public static <T> T get(final Iterator<T> iterator, final int index) {
- Objects.requireNonNull(iterator, "iterator");
- return IteratorUtils.get(iterator, index);
+ public static boolean isProperSubCollection(final Collection<?> a, final Collection<?> b) {
+ Objects.requireNonNull(a, "a");
+ Objects.requireNonNull(b, "b");
+ return a.size() < b.size() && CollectionUtils.isSubCollection(a, b);
}
/**
- * Ensures an index is not negative.
- * @param index the index to check.
- * @throws IndexOutOfBoundsException if the index is negative.
+ * Returns {@code true} iff <i>a</i> is a sub-collection of <i>b</i>,
+ * that is, iff the cardinality of <i>e</i> in <i>a</i> is less than or
+ * equal to the cardinality of <i>e</i> in <i>b</i>, for each element <i>e</i>
+ * in <i>a</i>.
+ *
+ * @param a the first (sub?) collection, must not be null
+ * @param b the second (super?) collection, must not be null
+ * @return {@code true} iff <i>a</i> is a sub-collection of <i>b</i>
+ * @throws NullPointerException if either collection is null
+ * @see #isProperSubCollection
+ * @see Collection#containsAll
*/
- static void checkIndexBounds(final int index) {
- if (index < 0) {
- throw new IndexOutOfBoundsException("Index cannot be negative: " + index);
+ public static boolean isSubCollection(final Collection<?> a, final Collection<?> b) {
+ Objects.requireNonNull(a, "a");
+ Objects.requireNonNull(b, "b");
+ final CardinalityHelper<Object> helper = new CardinalityHelper<>(a, b);
+ for (final Object obj : a) {
+ if (helper.freqA(obj) > helper.freqB(obj)) {
+ return false;
+ }
}
+ return true;
}
/**
- * Returns the {@code index}-th value in the {@code iterable}'s {@link Iterator}, throwing
- * {@code IndexOutOfBoundsException} if there is no such element.
+ * Answers true if a predicate is true for every element of a
+ * collection.
+ *
* <p>
- * If the {@link Iterable} is a {@link List}, then it will use {@link List#get(int)}.
+ * A {@code null} predicate returns false.
+ * </p>
+ * <p>
+ * A {@code null} or empty collection returns true.
* </p>
*
- * @param iterable the {@link Iterable} to get a value from
- * @param index the index to get
- * @param <T> the type of object in the {@link Iterable}.
- * @return the object at the specified index
- * @throws IndexOutOfBoundsException if the index is invalid
- * @deprecated since 4.1, use {@code IterableUtils.get(Iterable, int)} instead
+ * @param <C> the type of object the {@link Iterable} contains
+ * @param input the {@link Iterable} to get the input from, may be null
+ * @param predicate the predicate to use, may be null
+ * @return true if every element of the collection matches the predicate or if the
+ * collection is empty, false otherwise
+ * @since 4.0
+ * @deprecated since 4.1, use {@link IterableUtils#matchesAll(Iterable, Predicate)} instead
*/
@Deprecated
- public static <T> T get(final Iterable<T> iterable, final int index) {
- Objects.requireNonNull(iterable, "iterable");
- return IterableUtils.get(iterable, index);
+ public static <C> boolean matchesAll(final Iterable<C> input, final Predicate<? super C> predicate) {
+ return predicate != null && IterableUtils.matchesAll(input, predicate);
}
/**
- * Returns the {@code index}-th value in {@code object}, throwing
- * {@code IndexOutOfBoundsException} if there is no such element or
- * {@code IllegalArgumentException} if {@code object} is not an
- * instance of one of the supported types.
+ * Gets the maximum number of elements that the Collection can contain.
* <p>
- * The supported types, and associated semantics are:
+ * This method uses the {@link BoundedCollection} interface to determine the
+ * maximum size. If the collection does not implement this interface then
+ * -1 is returned.
+ * </p>
+ * <p>
+ * The collection does not have to implement this interface directly.
+ * If the collection has been decorated using the decorators subpackage
+ * then these will be removed to access the BoundedCollection.
* </p>
- * <ul>
- * <li> Map -- the value returned is the {@code Map.Entry} in position
- * {@code index} in the map's {@code entrySet} iterator,
- * if there is such an entry.</li>
- * <li> List -- this method is equivalent to the list's get method.</li>
- * <li> Array -- the {@code index}-th array entry is returned,
- * if there is such an entry; otherwise an {@code IndexOutOfBoundsException}
- * is thrown.</li>
- * <li> Collection -- the value returned is the {@code index}-th object
- * returned by the collection's default iterator, if there is such an element.</li>
- * <li> Iterator or Enumeration -- the value returned is the
- * {@code index}-th object in the Iterator/Enumeration, if there
- * is such an element. The Iterator/Enumeration is advanced to
- * {@code index} (or to the end, if {@code index} exceeds the
- * number of entries) as a side effect of this method.</li>
- * </ul>
*
- * @param object the object to get a value from
- * @param index the index to get
- * @return the object at the specified index
- * @throws IndexOutOfBoundsException if the index is invalid
- * @throws IllegalArgumentException if the object type is invalid
+ * @param collection the collection to check
+ * @return the maximum size of the BoundedCollection, -1 if no maximum size
+ * @throws NullPointerException if the collection is null
*/
- public static Object get(final Object object, final int index) {
- final int i = index;
- if (i < 0) {
- throw new IndexOutOfBoundsException("Index cannot be negative: " + i);
- }
- if (object instanceof Map<?, ?>) {
- final Map<?, ?> map = (Map<?, ?>) object;
- final Iterator<?> iterator = map.entrySet().iterator();
- return IteratorUtils.get(iterator, i);
- }
- if (object instanceof Object[]) {
- return ((Object[]) object)[i];
- }
- if (object instanceof Iterator<?>) {
- final Iterator<?> it = (Iterator<?>) object;
- return IteratorUtils.get(it, i);
- }
- if (object instanceof Iterable<?>) {
- final Iterable<?> iterable = (Iterable<?>) object;
- return IterableUtils.get(iterable, i);
- }
- if (object instanceof Enumeration<?>) {
- final Enumeration<?> it = (Enumeration<?>) object;
- return EnumerationUtils.get(it, i);
- }
- if (object == null) {
- throw new IllegalArgumentException("Unsupported object type: null");
+ public static int maxSize(final Collection<? extends Object> collection) {
+ Objects.requireNonNull(collection, "collection");
+ if (collection instanceof BoundedCollection) {
+ return ((BoundedCollection<?>) collection).maxSize();
}
try {
- return Array.get(object, i);
+ final BoundedCollection<?> bcoll =
+ UnmodifiableBoundedCollection.unmodifiableBoundedCollection(collection);
+ return bcoll.maxSize();
} catch (final IllegalArgumentException ex) {
- throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName());
+ return -1;
}
}
/**
- * Returns the {@code index}-th {@code Map.Entry} in the {@code map}'s {@code entrySet},
- * throwing {@code IndexOutOfBoundsException} if there is no such element.
+ * Returns a {@link Collection} of all the permutations of the input collection.
+ * <p>
+ * NOTE: the number of permutations of a given collection is equal to n!, where
+ * n is the size of the collection. Thus, the resulting collection will become
+ * <b>very</b> large for collections > 10 (e.g. 10! = 3628800, 15! = 1307674368000).
+ * </p>
+ * <p>
+ * For larger collections it is advised to use a {@link PermutationIterator} to
+ * iterate over all permutations.
+ * </p>
*
- * @param <K> the key type in the {@link Map}
- * @param <V> the value type in the {@link Map}
- * @param map the object to get a value from
- * @param index the index to get
- * @return the object at the specified index
- * @throws IndexOutOfBoundsException if the index is invalid
+ * @see PermutationIterator
+ *
+ * @param <E> the element type
+ * @param collection the collection to create permutations for, must not be null
+ * @return an unordered collection of all permutations of the input collection
+ * @throws NullPointerException if collection is null
+ * @since 4.0
*/
- public static <K, V> Map.Entry<K, V> get(final Map<K, V> map, final int index) {
- Objects.requireNonNull(map, "map");
- checkIndexBounds(index);
- return get(map.entrySet(), index);
+ public static <E> Collection<List<E>> permutations(final Collection<E> collection) {
+ Objects.requireNonNull(collection, "collection");
+ final PermutationIterator<E> it = new PermutationIterator<>(collection);
+ final Collection<List<E>> result = new ArrayList<>();
+ while (it.hasNext()) {
+ result.add(it.next());
+ }
+ return result;
}
/**
- * Gets the size of the collection/iterator specified.
+ * Returns a predicated (validating) collection backed by the given collection.
* <p>
- * This method can handles objects as follows
+ * Only objects that pass the test in the given predicate can be added to the collection.
+ * Trying to add an invalid object results in an IllegalArgumentException.
+ * It is important not to use the original collection after invoking this method,
+ * as it is a backdoor for adding invalid objects.
* </p>
- * <ul>
- * <li>Collection - the collection size
- * <li>Map - the map size
- * <li>Array - the array size
- * <li>Iterator - the number of elements remaining in the iterator
- * <li>Enumeration - the number of elements remaining in the enumeration
- * </ul>
*
- * @param object the object to get the size of, may be null
- * @return the size of the specified collection or 0 if the object was null
- * @throws IllegalArgumentException thrown if object is not recognized
- * @since 3.1
+ * @param <C> the type of objects in the Collection.
+ * @param collection the collection to predicate, must not be null
+ * @param predicate the predicate for the collection, must not be null
+ * @return a predicated collection backed by the given collection
+ * @throws NullPointerException if the collection or predicate is null
*/
- public static int size(final Object object) {
- if (object == null) {
- return 0;
- }
- int total = 0;
- if (object instanceof Map<?, ?>) {
- total = ((Map<?, ?>) object).size();
- } else if (object instanceof Collection<?>) {
- total = ((Collection<?>) object).size();
- } else if (object instanceof Iterable<?>) {
- total = IterableUtils.size((Iterable<?>) object);
- } else if (object instanceof Object[]) {
- total = ((Object[]) object).length;
- } else if (object instanceof Iterator<?>) {
- total = IteratorUtils.size((Iterator<?>) object);
- } else if (object instanceof Enumeration<?>) {
- final Enumeration<?> it = (Enumeration<?>) object;
- while (it.hasMoreElements()) {
- total++;
- it.nextElement();
- }
- } else {
- try {
- total = Array.getLength(object);
- } catch (final IllegalArgumentException ex) {
- throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName());
- }
- }
- return total;
+ public static <C> Collection<C> predicatedCollection(final Collection<C> collection,
+ final Predicate<? super C> predicate) {
+ Objects.requireNonNull(collection, "collection");
+ Objects.requireNonNull(predicate, "predicate");
+ return PredicatedCollection.predicatedCollection(collection, predicate);
}
/**
- * Checks if the specified collection/array/iterator is empty.
+ * Removes the elements in {@code remove} from {@code collection}. That is, this
+ * method returns a collection containing all the elements in {@code c}
+ * that are not in {@code remove}. The cardinality of an element {@code e}
+ * in the returned collection is the same as the cardinality of {@code e}
+ * in {@code collection} unless {@code remove} contains {@code e}, in which
+ * case the cardinality is zero. This method is useful if you do not wish to modify
+ * the collection {@code c} and thus cannot call {@code collection.removeAll(remove);}.
* <p>
- * This method can handles objects as follows
+ * This implementation iterates over {@code collection}, checking each element in
+ * turn to see if it's contained in {@code remove}. If it's not contained, it's added
+ * to the returned list. As a consequence, it is advised to use a collection type for
+ * {@code remove} that provides a fast (e.g. O(1)) implementation of
+ * {@link Collection#contains(Object)}.
* </p>
- * <ul>
- * <li>Collection - via collection isEmpty
- * <li>Map - via map isEmpty
- * <li>Array - using array size
- * <li>Iterator - via hasNext
- * <li>Enumeration - via hasMoreElements
- * </ul>
+ *
+ * @param <E> the type of object the {@link Collection} contains
+ * @param collection the collection from which items are removed (in the returned collection)
+ * @param remove the items to be removed from the returned {@code collection}
+ * @return a {@code Collection} containing all the elements of {@code collection} except
+ * any elements that also occur in {@code remove}.
+ * @throws NullPointerException if either parameter is null
+ * @since 4.0 (method existed in 3.2 but was completely broken)
+ */
+ public static <E> Collection<E> removeAll(final Collection<E> collection, final Collection<?> remove) {
+ return ListUtils.removeAll(collection, remove);
+ }
+
+ /**
+ * Removes all elements in {@code remove} from {@code collection}.
+ * That is, this method returns a collection containing all the elements in
+ * {@code collection} that are not in {@code remove}. The
+ * cardinality of an element {@code e} in the returned collection is
+ * the same as the cardinality of {@code e} in {@code collection}
+ * unless {@code remove} contains {@code e}, in which case the
+ * cardinality is zero. This method is useful if you do not wish to modify
+ * the collection {@code c} and thus cannot call
+ * {@code collection.removeAll(remove)}.
* <p>
- * Note: This method is named to avoid clashing with
- * {@link #isEmpty(Collection)}.
+ * Moreover this method uses an {@link Equator} instead of
+ * {@link Object#equals(Object)} to determine the equality of the elements
+ * in {@code collection} and {@code remove}. Hence this method is
+ * useful in cases where the equals behavior of an object needs to be
+ * modified without changing the object itself.
* </p>
*
- * @param object the object to get the size of, may be null
- * @return true if empty or null
- * @throws IllegalArgumentException thrown if object is not recognized
- * @since 3.2
+ * @param <E> the type of object the {@link Collection} contains
+ * @param collection the collection from which items are removed (in the returned collection)
+ * @param remove the items to be removed from the returned collection
+ * @param equator the Equator used for testing equality
+ * @return a {@code Collection} containing all the elements of {@code collection}
+ * except any element that if equal according to the {@code equator}
+ * @throws NullPointerException if any of the parameters is null
+ * @since 4.1
*/
- public static boolean sizeIsEmpty(final Object object) {
- if (object == null) {
- return true;
- }
- if (object instanceof Collection<?>) {
- return ((Collection<?>) object).isEmpty();
+ public static <E> Collection<E> removeAll(final Iterable<E> collection,
+ final Iterable<? extends E> remove,
+ final Equator<? super E> equator) {
+ Objects.requireNonNull(collection, "collection");
+ Objects.requireNonNull(remove, "remove");
+ Objects.requireNonNull(equator, "equator");
+ final Transformer<E, EquatorWrapper<E>> transformer = input -> new EquatorWrapper<>(equator, input);
+
+ final Set<EquatorWrapper<E>> removeSet =
+ collect(remove, transformer, new HashSet<>());
+
+ final List<E> list = new ArrayList<>();
+ for (final E element : collection) {
+ if (!removeSet.contains(new EquatorWrapper<>(equator, element))) {
+ list.add(element);
+ }
}
- if (object instanceof Iterable<?>) {
- return IterableUtils.isEmpty((Iterable<?>) object);
+ return list;
+ }
+
+ /**
+ * Removes the specified number of elements from the start index in the collection and returns them.
+ * This method modifies the input collections.
+ *
+ * @param <E> the type of object the {@link Collection} contains
+ * @param input the collection will be operated, can't be null
+ * @param startIndex the start index (inclusive) to remove element, can't be less than 0
+ * @param count the specified number to remove, can't be less than 1
+ * @return collection of elements that removed from the input collection
+ * @throws NullPointerException if input is null
+ * @since 4.5
+ */
+ public static <E> Collection<E> removeCount(final Collection<E> input, int startIndex, int count) {
+ Objects.requireNonNull(input, "input");
+ if (startIndex < 0) {
+ throw new IndexOutOfBoundsException("The start index can't be less than 0.");
}
- if (object instanceof Map<?, ?>) {
- return ((Map<?, ?>) object).isEmpty();
+ if (count < 0) {
+ throw new IndexOutOfBoundsException("The count can't be less than 0.");
}
- if (object instanceof Object[]) {
- return ((Object[]) object).length == 0;
+ if (input.size() < startIndex + count) {
+ throw new IndexOutOfBoundsException(
+ "The sum of start index and count can't be greater than the size of collection.");
}
- if (object instanceof Iterator<?>) {
- return !((Iterator<?>) object).hasNext();
+
+ final Collection<E> result = new ArrayList<>(count);
+ final Iterator<E> iterator = input.iterator();
+ while (count > 0) {
+ if (startIndex > 0) {
+ startIndex -= 1;
+ iterator.next();
+ continue;
+ }
+ count -= 1;
+ result.add(iterator.next());
+ iterator.remove();
}
- if (object instanceof Enumeration<?>) {
- return !((Enumeration<?>) object).hasMoreElements();
+ return result;
+ }
+
+ /**
+ * Removes elements whose index are between startIndex, inclusive and endIndex,
+ * exclusive in the collection and returns them.
+ * This method modifies the input collections.
+ *
+ * @param <E> the type of object the {@link Collection} contains
+ * @param input the collection will be operated, must not be null
+ * @param startIndex the start index (inclusive) to remove element, must not be less than 0
+ * @param endIndex the end index (exclusive) to remove, must not be less than startIndex
+ * @return collection of elements that removed from the input collection
+ * @throws NullPointerException if input is null
+ * @since 4.5
+ */
+ public static <E> Collection<E> removeRange(final Collection<E> input, final int startIndex, final int endIndex) {
+ Objects.requireNonNull(input, "input");
+ if (endIndex < startIndex) {
+ throw new IllegalArgumentException("The end index can't be less than the start index.");
}
- try {
- return Array.getLength(object) == 0;
- } catch (final IllegalArgumentException ex) {
- throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName());
+ if (input.size() < endIndex) {
+ throw new IndexOutOfBoundsException("The end index can't be greater than the size of collection.");
}
+ return CollectionUtils.removeCount(input, startIndex, endIndex - startIndex);
}
/**
- * Null-safe check if the specified collection is empty.
+ * Returns a collection containing all the elements in {@code collection}
+ * that are also in {@code retain}. The cardinality of an element {@code e}
+ * in the returned collection is the same as the cardinality of {@code e}
+ * in {@code collection} unless {@code retain} does not contain {@code e}, in which
+ * case the cardinality is zero. This method is useful if you do not wish to modify
+ * the collection {@code c} and thus cannot call {@code c.retainAll(retain);}.
* <p>
- * Null returns true.
+ * This implementation iterates over {@code collection}, checking each element in
+ * turn to see if it's contained in {@code retain}. If it's contained, it's added
+ * to the returned list. As a consequence, it is advised to use a collection type for
+ * {@code retain} that provides a fast (e.g. O(1)) implementation of
+ * {@link Collection#contains(Object)}.
* </p>
*
- * @param coll the collection to check, may be null
- * @return true if empty or null
+ * @param <C> the type of object the {@link Collection} contains
+ * @param collection the collection whose contents are the target of the #retailAll operation
+ * @param retain the collection containing the elements to be retained in the returned collection
+ * @return a {@code Collection} containing all the elements of {@code collection}
+ * that occur at least once in {@code retain}.
+ * @throws NullPointerException if either parameter is null
* @since 3.2
*/
- public static boolean isEmpty(final Collection<?> coll) {
- return coll == null || coll.isEmpty();
+ public static <C> Collection<C> retainAll(final Collection<C> collection, final Collection<?> retain) {
+ Objects.requireNonNull(collection, "collection");
+ Objects.requireNonNull(retain, "retain");
+ return ListUtils.retainAll(collection, retain);
}
/**
- * Null-safe check if the specified collection is not empty.
+ * Returns a collection containing all the elements in
+ * {@code collection} that are also in {@code retain}. The
+ * cardinality of an element {@code e} in the returned collection is
+ * the same as the cardinality of {@code e} in {@code collection}
+ * unless {@code retain} does not contain {@code e}, in which case
+ * the cardinality is zero. This method is useful if you do not wish to
+ * modify the collection {@code c} and thus cannot call
+ * {@code c.retainAll(retain);}.
* <p>
- * Null returns false.
+ * Moreover this method uses an {@link Equator} instead of
+ * {@link Object#equals(Object)} to determine the equality of the elements
+ * in {@code collection} and {@code retain}. Hence this method is
+ * useful in cases where the equals behavior of an object needs to be
+ * modified without changing the object itself.
* </p>
*
- * @param coll the collection to check, may be null
- * @return true if non-null and non-empty
- * @since 3.2
+ * @param <E> the type of object the {@link Collection} contains
+ * @param collection the collection whose contents are the target of the {@code retainAll} operation
+ * @param retain the collection containing the elements to be retained in the returned collection
+ * @param equator the Equator used for testing equality
+ * @return a {@code Collection} containing all the elements of {@code collection}
+ * that occur at least once in {@code retain} according to the {@code equator}
+ * @throws NullPointerException if any of the parameters is null
+ * @since 4.1
*/
- public static boolean isNotEmpty(final Collection<?> coll) {
- return !isEmpty(coll);
+ public static <E> Collection<E> retainAll(final Iterable<E> collection,
+ final Iterable<? extends E> retain,
+ final Equator<? super E> equator) {
+ Objects.requireNonNull(collection, "collection");
+ Objects.requireNonNull(retain, "retain");
+ Objects.requireNonNull(equator, "equator");
+ final Transformer<E, EquatorWrapper<E>> transformer = input -> new EquatorWrapper<>(equator, input);
+
+ final Set<EquatorWrapper<E>> retainSet =
+ collect(retain, transformer, new HashSet<>());
+
+ final List<E> list = new ArrayList<>();
+ for (final E element : collection) {
+ if (retainSet.contains(new EquatorWrapper<>(equator, element))) {
+ list.add(element);
+ }
+ }
+ return list;
}
/**
@@ -1626,413 +1698,312 @@ public class CollectionUtils {
}
/**
- * Returns true if no more elements can be added to the Collection.
- * <p>
- * This method uses the {@link BoundedCollection} interface to determine the
- * full status. If the collection does not implement this interface then
- * false is returned.
- * </p>
- * <p>
- * The collection does not have to implement this interface directly.
- * If the collection has been decorated using the decorators subpackage
- * then these will be removed to access the BoundedCollection.
- * </p>
- *
- * @param collection the collection to check
- * @return true if the BoundedCollection is full
- * @throws NullPointerException if the collection is null
- */
- public static boolean isFull(final Collection<? extends Object> collection) {
- Objects.requireNonNull(collection, "collection");
- if (collection instanceof BoundedCollection) {
- return ((BoundedCollection<?>) collection).isFull();
- }
- try {
- final BoundedCollection<?> bcoll =
- UnmodifiableBoundedCollection.unmodifiableBoundedCollection(collection);
- return bcoll.isFull();
- } catch (final IllegalArgumentException ex) {
- return false;
- }
- }
-
- /**
- * Gets the maximum number of elements that the Collection can contain.
- * <p>
- * This method uses the {@link BoundedCollection} interface to determine the
- * maximum size. If the collection does not implement this interface then
- * -1 is returned.
- * </p>
+ * Selects all elements from input collection which match the given
+ * predicate into an output collection.
* <p>
- * The collection does not have to implement this interface directly.
- * If the collection has been decorated using the decorators subpackage
- * then these will be removed to access the BoundedCollection.
+ * A {@code null} predicate matches no elements.
* </p>
*
- * @param collection the collection to check
- * @return the maximum size of the BoundedCollection, -1 if no maximum size
- * @throws NullPointerException if the collection is null
+ * @param <O> the type of object the {@link Iterable} contains
+ * @param inputCollection the collection to get the input from, may not be null
+ * @param predicate the predicate to use, may be null
+ * @return the elements matching the predicate (new list)
*/
- public static int maxSize(final Collection<? extends Object> collection) {
- Objects.requireNonNull(collection, "collection");
- if (collection instanceof BoundedCollection) {
- return ((BoundedCollection<?>) collection).maxSize();
- }
- try {
- final BoundedCollection<?> bcoll =
- UnmodifiableBoundedCollection.unmodifiableBoundedCollection(collection);
- return bcoll.maxSize();
- } catch (final IllegalArgumentException ex) {
- return -1;
+ public static <O> Collection<O> select(final Iterable<? extends O> inputCollection,
+ final Predicate<? super O> predicate) {
+ int size = 0;
+ if (null != inputCollection) {
+ size = inputCollection instanceof Collection<?> ? ((Collection<?>) inputCollection).size() : 0;
}
+ final Collection<O> answer = size == 0 ? new ArrayList<>() : new ArrayList<>(size);
+ return select(inputCollection, predicate, answer);
}
/**
- * Merges two sorted Collections, a and b, into a single, sorted List
- * such that the natural ordering of the elements is retained.
- * <p>
- * Uses the standard O(n) merge algorithm for combining two sorted lists.
- * </p>
- *
- * @param <O> the element type
- * @param a the first collection, must not be null
- * @param b the second collection, must not be null
- * @return a new sorted List, containing the elements of Collection a and b
- * @throws NullPointerException if either collection is null
- * @since 4.0
- */
- public static <O extends Comparable<? super O>> List<O> collate(final Iterable<? extends O> a,
- final Iterable<? extends O> b) {
- return collate(a, b, ComparatorUtils.<O>naturalComparator(), true);
- }
-
- /**
- * Merges two sorted Collections, a and b, into a single, sorted List
- * such that the natural ordering of the elements is retained.
- * <p>
- * Uses the standard O(n) merge algorithm for combining two sorted lists.
- * </p>
- *
- * @param <O> the element type
- * @param a the first collection, must not be null
- * @param b the second collection, must not be null
- * @param includeDuplicates if {@code true} duplicate elements will be retained, otherwise
- * they will be removed in the output collection
- * @return a new sorted List, containing the elements of Collection a and b
- * @throws NullPointerException if either collection is null
- * @since 4.0
- */
- public static <O extends Comparable<? super O>> List<O> collate(final Iterable<? extends O> a,
- final Iterable<? extends O> b,
- final boolean includeDuplicates) {
- return collate(a, b, ComparatorUtils.<O>naturalComparator(), includeDuplicates);
- }
-
- /**
- * Merges two sorted Collections, a and b, into a single, sorted List
- * such that the ordering of the elements according to Comparator c is retained.
- * <p>
- * Uses the standard O(n) merge algorithm for combining two sorted lists.
- * </p>
- *
- * @param <O> the element type
- * @param a the first collection, must not be null
- * @param b the second collection, must not be null
- * @param c the comparator to use for the merge.
- * @return a new sorted List, containing the elements of Collection a and b
- * @throws NullPointerException if either collection or the comparator is null
- * @since 4.0
- */
- public static <O> List<O> collate(final Iterable<? extends O> a, final Iterable<? extends O> b,
- final Comparator<? super O> c) {
- return collate(a, b, c, true);
- }
-
- /**
- * Merges two sorted Collections, a and b, into a single, sorted List
- * such that the ordering of the elements according to Comparator c is retained.
+ * Selects all elements from input collection which match the given
+ * predicate and adds them to outputCollection.
* <p>
- * Uses the standard O(n) merge algorithm for combining two sorted lists.
+ * If the input collection or predicate is null, there is no change to the
+ * output collection.
* </p>
*
- * @param <O> the element type
- * @param iterableA the first collection, must not be null
- * @param iterableB the second collection, must not be null
- * @param comparator the comparator to use for the merge.
- * @param includeDuplicates if {@code true} duplicate elements will be retained, otherwise
- * they will be removed in the output collection
- * @return a new sorted List, containing the elements of Collection a and b
- * @throws NullPointerException if either collection or the comparator is null
- * @since 4.0
+ * @param <O> the type of object the {@link Iterable} contains
+ * @param <R> the type of the output {@link Collection}
+ * @param inputCollection the collection to get the input from, may be null
+ * @param predicate the predicate to use, may be null
+ * @param outputCollection the collection to output into, may not be null if the inputCollection
+ * and predicate or not null
+ * @return the outputCollection
*/
- public static <O> List<O> collate(final Iterable<? extends O> iterableA, final Iterable<? extends O> iterableB,
- final Comparator<? super O> comparator, final boolean includeDuplicates) {
-
- Objects.requireNonNull(iterableA, "iterableA");
- Objects.requireNonNull(iterableB, "iterableB");
- Objects.requireNonNull(comparator, "comparator");
-
- // if both Iterables are a Collection, we can estimate the size
- final int totalSize = iterableA instanceof Collection<?> && iterableB instanceof Collection<?> ?
- Math.max(1, ((Collection<?>) iterableA).size() + ((Collection<?>) iterableB).size()) : 10;
-
- final Iterator<O> iterator = new CollatingIterator<>(comparator, iterableA.iterator(), iterableB.iterator());
- if (includeDuplicates) {
- return IteratorUtils.toList(iterator, totalSize);
- }
- final ArrayList<O> mergedList = new ArrayList<>(totalSize);
+ public static <O, R extends Collection<? super O>> R select(final Iterable<? extends O> inputCollection,
+ final Predicate<? super O> predicate, final R outputCollection) {
- O lastItem = null;
- while (iterator.hasNext()) {
- final O item = iterator.next();
- if (lastItem == null || !lastItem.equals(item)) {
- mergedList.add(item);
+ if (inputCollection != null && predicate != null) {
+ for (final O item : inputCollection) {
+ if (predicate.evaluate(item)) {
+ outputCollection.add(item);
+ }
}
- lastItem = item;
}
-
- mergedList.trimToSize();
- return mergedList;
+ return outputCollection;
}
/**
- * Returns a {@link Collection} of all the permutations of the input collection.
+ * Selects all elements from inputCollection into an output and rejected collection,
+ * based on the evaluation of the given predicate.
* <p>
- * NOTE: the number of permutations of a given collection is equal to n!, where
- * n is the size of the collection. Thus, the resulting collection will become
- * <b>very</b> large for collections > 10 (e.g. 10! = 3628800, 15! = 1307674368000).
+ * Elements matching the predicate are added to the {@code outputCollection},
+ * all other elements are added to the {@code rejectedCollection}.
* </p>
* <p>
- * For larger collections it is advised to use a {@link PermutationIterator} to
- * iterate over all permutations.
+ * If the input predicate is {@code null}, no elements are added to
+ * {@code outputCollection} or {@code rejectedCollection}.
* </p>
+ * <p>
+ * Note: calling the method is equivalent to the following code snippet:
+ * </p>
+ * <pre>
+ * select(inputCollection, predicate, outputCollection);
+ * selectRejected(inputCollection, predicate, rejectedCollection);
+ * </pre>
*
- * @see PermutationIterator
- *
- * @param <E> the element type
- * @param collection the collection to create permutations for, must not be null
- * @return an unordered collection of all permutations of the input collection
- * @throws NullPointerException if collection is null
- * @since 4.0
+ * @param <O> the type of object the {@link Iterable} contains
+ * @param <R> the type of the output {@link Collection}
+ * @param inputCollection the collection to get the input from, may be null
+ * @param predicate the predicate to use, may be null
+ * @param outputCollection the collection to output selected elements into, may not be null if the
+ * inputCollection and predicate are not null
+ * @param rejectedCollection the collection to output rejected elements into, may not be null if the
+ * inputCollection or predicate are not null
+ * @return the outputCollection
+ * @since 4.1
*/
- public static <E> Collection<List<E>> permutations(final Collection<E> collection) {
- Objects.requireNonNull(collection, "collection");
- final PermutationIterator<E> it = new PermutationIterator<>(collection);
- final Collection<List<E>> result = new ArrayList<>();
- while (it.hasNext()) {
- result.add(it.next());
+ public static <O, R extends Collection<? super O>> R select(final Iterable<? extends O> inputCollection,
+ final Predicate<? super O> predicate, final R outputCollection, final R rejectedCollection) {
+
+ if (inputCollection != null && predicate != null) {
+ for (final O element : inputCollection) {
+ if (predicate.evaluate(element)) {
+ outputCollection.add(element);
+ } else {
+ rejectedCollection.add(element);
+ }
+ }
}
- return result;
+ return outputCollection;
}
/**
- * Returns a collection containing all the elements in {@code collection}
- * that are also in {@code retain}. The cardinality of an element {@code e}
- * in the returned collection is the same as the cardinality of {@code e}
- * in {@code collection} unless {@code retain} does not contain {@code e}, in which
- * case the cardinality is zero. This method is useful if you do not wish to modify
- * the collection {@code c} and thus cannot call {@code c.retainAll(retain);}.
+ * Selects all elements from inputCollection which don't match the given
+ * predicate into an output collection.
* <p>
- * This implementation iterates over {@code collection}, checking each element in
- * turn to see if it's contained in {@code retain}. If it's contained, it's added
- * to the returned list. As a consequence, it is advised to use a collection type for
- * {@code retain} that provides a fast (e.g. O(1)) implementation of
- * {@link Collection#contains(Object)}.
+ * If the input predicate is {@code null}, the result is an empty
+ * list.
* </p>
*
- * @param <C> the type of object the {@link Collection} contains
- * @param collection the collection whose contents are the target of the #retailAll operation
- * @param retain the collection containing the elements to be retained in the returned collection
- * @return a {@code Collection} containing all the elements of {@code collection}
- * that occur at least once in {@code retain}.
- * @throws NullPointerException if either parameter is null
- * @since 3.2
+ * @param <O> the type of object the {@link Iterable} contains
+ * @param inputCollection the collection to get the input from, may not be null
+ * @param predicate the predicate to use, may be null
+ * @return the elements <b>not</b> matching the predicate (new list)
*/
- public static <C> Collection<C> retainAll(final Collection<C> collection, final Collection<?> retain) {
- Objects.requireNonNull(collection, "collection");
- Objects.requireNonNull(retain, "retain");
- return ListUtils.retainAll(collection, retain);
+ public static <O> Collection<O> selectRejected(final Iterable<? extends O> inputCollection,
+ final Predicate<? super O> predicate) {
+ int size = 0;
+ if (null != inputCollection) {
+ size = inputCollection instanceof Collection<?> ? ((Collection<?>) inputCollection).size() : 0;
+ }
+ final Collection<O> answer = size == 0 ? new ArrayList<>() : new ArrayList<>(size);
+ return selectRejected(inputCollection, predicate, answer);
}
/**
- * Returns a collection containing all the elements in
- * {@code collection} that are also in {@code retain}. The
- * cardinality of an element {@code e} in the returned collection is
- * the same as the cardinality of {@code e} in {@code collection}
- * unless {@code retain} does not contain {@code e}, in which case
- * the cardinality is zero. This method is useful if you do not wish to
- * modify the collection {@code c} and thus cannot call
- * {@code c.retainAll(retain);}.
+ * Selects all elements from inputCollection which don't match the given
+ * predicate and adds them to outputCollection.
* <p>
- * Moreover this method uses an {@link Equator} instead of
- * {@link Object#equals(Object)} to determine the equality of the elements
- * in {@code collection} and {@code retain}. Hence this method is
- * useful in cases where the equals behavior of an object needs to be
- * modified without changing the object itself.
+ * If the input predicate is {@code null}, no elements are added to
+ * {@code outputCollection}.
* </p>
*
- * @param <E> the type of object the {@link Collection} contains
- * @param collection the collection whose contents are the target of the {@code retainAll} operation
- * @param retain the collection containing the elements to be retained in the returned collection
- * @param equator the Equator used for testing equality
- * @return a {@code Collection} containing all the elements of {@code collection}
- * that occur at least once in {@code retain} according to the {@code equator}
- * @throws NullPointerException if any of the parameters is null
- * @since 4.1
+ * @param <O> the type of object the {@link Iterable} contains
+ * @param <R> the type of the output {@link Collection}
+ * @param inputCollection the collection to get the input from, may be null
+ * @param predicate the predicate to use, may be null
+ * @param outputCollection the collection to output into, may not be null if the inputCollection
+ * and predicate or not null
+ * @return outputCollection
*/
- public static <E> Collection<E> retainAll(final Iterable<E> collection,
- final Iterable<? extends E> retain,
- final Equator<? super E> equator) {
- Objects.requireNonNull(collection, "collection");
- Objects.requireNonNull(retain, "retain");
- Objects.requireNonNull(equator, "equator");
- final Transformer<E, EquatorWrapper<E>> transformer = input -> new EquatorWrapper<>(equator, input);
-
- final Set<EquatorWrapper<E>> retainSet =
- collect(retain, transformer, new HashSet<>());
+ public static <O, R extends Collection<? super O>> R selectRejected(final Iterable<? extends O> inputCollection,
+ final Predicate<? super O> predicate, final R outputCollection) {
- final List<E> list = new ArrayList<>();
- for (final E element : collection) {
- if (retainSet.contains(new EquatorWrapper<>(equator, element))) {
- list.add(element);
+ if (inputCollection != null && predicate != null) {
+ for (final O item : inputCollection) {
+ if (!predicate.evaluate(item)) {
+ outputCollection.add(item);
+ }
}
}
- return list;
+ return outputCollection;
}
/**
- * Removes elements whose index are between startIndex, inclusive and endIndex,
- * exclusive in the collection and returns them.
- * This method modifies the input collections.
+ * Gets the size of the collection/iterator specified.
+ * <p>
+ * This method can handles objects as follows
+ * </p>
+ * <ul>
+ * <li>Collection - the collection size
+ * <li>Map - the map size
+ * <li>Array - the array size
+ * <li>Iterator - the number of elements remaining in the iterator
+ * <li>Enumeration - the number of elements remaining in the enumeration
+ * </ul>
*
- * @param <E> the type of object the {@link Collection} contains
- * @param input the collection will be operated, must not be null
- * @param startIndex the start index (inclusive) to remove element, must not be less than 0
- * @param endIndex the end index (exclusive) to remove, must not be less than startIndex
- * @return collection of elements that removed from the input collection
- * @throws NullPointerException if input is null
- * @since 4.5
+ * @param object the object to get the size of, may be null
+ * @return the size of the specified collection or 0 if the object was null
+ * @throws IllegalArgumentException thrown if object is not recognized
+ * @since 3.1
*/
- public static <E> Collection<E> removeRange(final Collection<E> input, final int startIndex, final int endIndex) {
- Objects.requireNonNull(input, "input");
- if (endIndex < startIndex) {
- throw new IllegalArgumentException("The end index can't be less than the start index.");
+ public static int size(final Object object) {
+ if (object == null) {
+ return 0;
}
- if (input.size() < endIndex) {
- throw new IndexOutOfBoundsException("The end index can't be greater than the size of collection.");
+ int total = 0;
+ if (object instanceof Map<?, ?>) {
+ total = ((Map<?, ?>) object).size();
+ } else if (object instanceof Collection<?>) {
+ total = ((Collection<?>) object).size();
+ } else if (object instanceof Iterable<?>) {
+ total = IterableUtils.size((Iterable<?>) object);
+ } else if (object instanceof Object[]) {
+ total = ((Object[]) object).length;
+ } else if (object instanceof Iterator<?>) {
+ total = IteratorUtils.size((Iterator<?>) object);
+ } else if (object instanceof Enumeration<?>) {
+ final Enumeration<?> it = (Enumeration<?>) object;
+ while (it.hasMoreElements()) {
+ total++;
+ it.nextElement();
+ }
+ } else {
+ try {
+ total = Array.getLength(object);
+ } catch (final IllegalArgumentException ex) {
+ throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName());
+ }
}
- return CollectionUtils.removeCount(input, startIndex, endIndex - startIndex);
+ return total;
}
/**
- * Removes the specified number of elements from the start index in the collection and returns them.
- * This method modifies the input collections.
+ * Checks if the specified collection/array/iterator is empty.
+ * <p>
+ * This method can handles objects as follows
+ * </p>
+ * <ul>
+ * <li>Collection - via collection isEmpty
+ * <li>Map - via map isEmpty
+ * <li>Array - using array size
+ * <li>Iterator - via hasNext
+ * <li>Enumeration - via hasMoreElements
+ * </ul>
+ * <p>
+ * Note: This method is named to avoid clashing with
+ * {@link #isEmpty(Collection)}.
+ * </p>
*
- * @param <E> the type of object the {@link Collection} contains
- * @param input the collection will be operated, can't be null
- * @param startIndex the start index (inclusive) to remove element, can't be less than 0
- * @param count the specified number to remove, can't be less than 1
- * @return collection of elements that removed from the input collection
- * @throws NullPointerException if input is null
- * @since 4.5
+ * @param object the object to get the size of, may be null
+ * @return true if empty or null
+ * @throws IllegalArgumentException thrown if object is not recognized
+ * @since 3.2
*/
- public static <E> Collection<E> removeCount(final Collection<E> input, int startIndex, int count) {
- Objects.requireNonNull(input, "input");
- if (startIndex < 0) {
- throw new IndexOutOfBoundsException("The start index can't be less than 0.");
+ public static boolean sizeIsEmpty(final Object object) {
+ if (object == null) {
+ return true;
+ }
+ if (object instanceof Collection<?>) {
+ return ((Collection<?>) object).isEmpty();
+ }
+ if (object instanceof Iterable<?>) {
+ return IterableUtils.isEmpty((Iterable<?>) object);
}
- if (count < 0) {
- throw new IndexOutOfBoundsException("The count can't be less than 0.");
+ if (object instanceof Map<?, ?>) {
+ return ((Map<?, ?>) object).isEmpty();
}
- if (input.size() < startIndex + count) {
- throw new IndexOutOfBoundsException(
- "The sum of start index and count can't be greater than the size of collection.");
+ if (object instanceof Object[]) {
+ return ((Object[]) object).length == 0;
}
-
- final Collection<E> result = new ArrayList<>(count);
- final Iterator<E> iterator = input.iterator();
- while (count > 0) {
- if (startIndex > 0) {
- startIndex -= 1;
- iterator.next();
- continue;
- }
- count -= 1;
- result.add(iterator.next());
- iterator.remove();
+ if (object instanceof Iterator<?>) {
+ return !((Iterator<?>) object).hasNext();
+ }
+ if (object instanceof Enumeration<?>) {
+ return !((Enumeration<?>) object).hasMoreElements();
+ }
+ try {
+ return Array.getLength(object) == 0;
+ } catch (final IllegalArgumentException ex) {
+ throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName());
}
- return result;
}
/**
- * Removes the elements in {@code remove} from {@code collection}. That is, this
- * method returns a collection containing all the elements in {@code c}
- * that are not in {@code remove}. The cardinality of an element {@code e}
- * in the returned collection is the same as the cardinality of {@code e}
- * in {@code collection} unless {@code remove} contains {@code e}, in which
- * case the cardinality is zero. This method is useful if you do not wish to modify
- * the collection {@code c} and thus cannot call {@code collection.removeAll(remove);}.
- * <p>
- * This implementation iterates over {@code collection}, checking each element in
- * turn to see if it's contained in {@code remove}. If it's not contained, it's added
- * to the returned list. As a consequence, it is advised to use a collection type for
- * {@code remove} that provides a fast (e.g. O(1)) implementation of
- * {@link Collection#contains(Object)}.
- * </p>
+ * Returns a new {@link Collection} containing {@code <i>a</i> - <i>b</i>}.
+ * The cardinality of each element <i>e</i> in the returned {@link Collection}
+ * will be the cardinality of <i>e</i> in <i>a</i> minus the cardinality
+ * of <i>e</i> in <i>b</i>, or zero, whichever is greater.
*
- * @param <E> the type of object the {@link Collection} contains
- * @param collection the collection from which items are removed (in the returned collection)
- * @param remove the items to be removed from the returned {@code collection}
- * @return a {@code Collection} containing all the elements of {@code collection} except
- * any elements that also occur in {@code remove}.
- * @throws NullPointerException if either parameter is null
- * @since 4.0 (method existed in 3.2 but was completely broken)
+ * @param a the collection to subtract from, must not be null
+ * @param b the collection to subtract, must not be null
+ * @param <O> the generic type that is able to represent the types contained
+ * in both input collections.
+ * @return a new collection with the results
+ * @see Collection#removeAll
*/
- public static <E> Collection<E> removeAll(final Collection<E> collection, final Collection<?> remove) {
- return ListUtils.removeAll(collection, remove);
+ public static <O> Collection<O> subtract(final Iterable<? extends O> a, final Iterable<? extends O> b) {
+ final Predicate<O> p = TruePredicate.truePredicate();
+ return subtract(a, b, p);
}
/**
- * Removes all elements in {@code remove} from {@code collection}.
- * That is, this method returns a collection containing all the elements in
- * {@code collection} that are not in {@code remove}. The
- * cardinality of an element {@code e} in the returned collection is
- * the same as the cardinality of {@code e} in {@code collection}
- * unless {@code remove} contains {@code e}, in which case the
- * cardinality is zero. This method is useful if you do not wish to modify
- * the collection {@code c} and thus cannot call
- * {@code collection.removeAll(remove)}.
+ * Returns a new {@link Collection} containing <i>a</i> minus a subset of
+ * <i>b</i>. Only the elements of <i>b</i> that satisfy the predicate
+ * condition, <i>p</i> are subtracted from <i>a</i>.
+ *
* <p>
- * Moreover this method uses an {@link Equator} instead of
- * {@link Object#equals(Object)} to determine the equality of the elements
- * in {@code collection} and {@code remove}. Hence this method is
- * useful in cases where the equals behavior of an object needs to be
- * modified without changing the object itself.
+ * The cardinality of each element <i>e</i> in the returned {@link Collection}
+ * that satisfies the predicate condition will be the cardinality of <i>e</i> in <i>a</i>
+ * minus the cardinality of <i>e</i> in <i>b</i>, or zero, whichever is greater.
+ * </p>
+ * <p>
+ * The cardinality of each element <i>e</i> in the returned {@link Collection} that does <b>not</b>
+ * satisfy the predicate condition will be equal to the cardinality of <i>e</i> in <i>a</i>.
* </p>
*
- * @param <E> the type of object the {@link Collection} contains
- * @param collection the collection from which items are removed (in the returned collection)
- * @param remove the items to be removed from the returned collection
- * @param equator the Equator used for testing equality
- * @return a {@code Collection} containing all the elements of {@code collection}
- * except any element that if equal according to the {@code equator}
- * @throws NullPointerException if any of the parameters is null
- * @since 4.1
+ * @param a the collection to subtract from, must not be null
+ * @param b the collection to subtract, must not be null
+ * @param p the condition used to determine which elements of <i>b</i> are
+ * subtracted.
+ * @param <O> the generic type that is able to represent the types contained
+ * in both input collections.
+ * @return a new collection with the results
+ * @throws NullPointerException if either collection or p is null
+ * @since 4.0
+ * @see Collection#removeAll
*/
- public static <E> Collection<E> removeAll(final Iterable<E> collection,
- final Iterable<? extends E> remove,
- final Equator<? super E> equator) {
- Objects.requireNonNull(collection, "collection");
- Objects.requireNonNull(remove, "remove");
- Objects.requireNonNull(equator, "equator");
- final Transformer<E, EquatorWrapper<E>> transformer = input -> new EquatorWrapper<>(equator, input);
-
- final Set<EquatorWrapper<E>> removeSet =
- collect(remove, transformer, new HashSet<>());
-
- final List<E> list = new ArrayList<>();
- for (final E element : collection) {
- if (!removeSet.contains(new EquatorWrapper<>(equator, element))) {
+ public static <O> Collection<O> subtract(final Iterable<? extends O> a,
+ final Iterable<? extends O> b,
+ final Predicate<O> p) {
+ Objects.requireNonNull(a, "a");
+ Objects.requireNonNull(b, "b");
+ Objects.requireNonNull(p, "p");
+ final ArrayList<O> list = new ArrayList<>();
+ final HashBag<O> bag = new HashBag<>();
+ for (final O element : b) {
+ if (p.evaluate(element)) {
+ bag.add(element);
+ }
+ }
+ for (final O element : a) {
+ if (!bag.remove(element, 1)) {
list.add(element);
}
}
@@ -2071,43 +2042,40 @@ public class CollectionUtils {
}
/**
- * Returns an unmodifiable collection backed by the given collection.
+ * Transform the collection by applying a Transformer to each element.
* <p>
- * This method uses the implementation in the decorators subpackage.
+ * If the input collection or transformer is null, there is no change made.
* </p>
- *
- * @param <C> the type of object the {@link Collection} contains
- * @param collection the collection to make unmodifiable, must not be null
- * @return an unmodifiable collection backed by the given collection
- * @throws NullPointerException if the collection is null
- * @deprecated since 4.1, use {@link java.util.Collections#unmodifiableCollection(Collection)} instead
- */
- @Deprecated
- public static <C> Collection<C> unmodifiableCollection(final Collection<? extends C> collection) {
- Objects.requireNonNull(collection, "collection");
- return UnmodifiableCollection.unmodifiableCollection(collection);
- }
-
- /**
- * Returns a predicated (validating) collection backed by the given collection.
* <p>
- * Only objects that pass the test in the given predicate can be added to the collection.
- * Trying to add an invalid object results in an IllegalArgumentException.
- * It is important not to use the original collection after invoking this method,
- * as it is a backdoor for adding invalid objects.
+ * This routine is best for Lists, for which set() is used to do the
+ * transformations "in place." For other Collections, clear() and addAll()
+ * are used to replace elements.
+ * </p>
+ * <p>
+ * If the input collection controls its input, such as a Set, and the
+ * Transformer creates duplicates (or are otherwise invalid), the collection
+ * may reduce in size due to calling this method.
* </p>
*
- * @param <C> the type of objects in the Collection.
- * @param collection the collection to predicate, must not be null
- * @param predicate the predicate for the collection, must not be null
- * @return a predicated collection backed by the given collection
- * @throws NullPointerException if the collection or predicate is null
+ * @param <C> the type of object the {@link Collection} contains
+ * @param collection the {@link Collection} to get the input from, may be null
+ * @param transformer the transformer to perform, may be null
*/
- public static <C> Collection<C> predicatedCollection(final Collection<C> collection,
- final Predicate<? super C> predicate) {
- Objects.requireNonNull(collection, "collection");
- Objects.requireNonNull(predicate, "predicate");
- return PredicatedCollection.predicatedCollection(collection, predicate);
+ public static <C> void transform(final Collection<C> collection,
+ final Transformer<? super C, ? extends C> transformer) {
+
+ if (collection != null && transformer != null) {
+ if (collection instanceof List<?>) {
+ final List<C> list = (List<C>) collection;
+ for (final ListIterator<C> it = list.listIterator(); it.hasNext();) {
+ it.set(transformer.transform(it.next()));
+ }
+ } else {
+ final Collection<C> resultCollection = collect(collection, transformer);
+ collection.clear();
+ collection.addAll(resultCollection);
+ }
+ }
}
/**
@@ -2136,20 +2104,52 @@ public class CollectionUtils {
}
/**
- * Extract the lone element of the specified Collection.
+ * Returns a {@link Collection} containing the union of the given
+ * {@link Iterable}s.
+ * <p>
+ * The cardinality of each element in the returned {@link Collection} will
+ * be equal to the maximum of the cardinality of that element in the two
+ * given {@link Iterable}s.
+ * </p>
*
- * @param <E> collection type
- * @param collection to read
- * @return sole member of collection
- * @throws NullPointerException if collection is null
- * @throws IllegalArgumentException if collection is empty or contains more than one element
- * @since 4.0
+ * @param a the first collection, must not be null
+ * @param b the second collection, must not be null
+ * @param <O> the generic type that is able to represent the types contained
+ * in both input collections.
+ * @return the union of the two collections
+ * @throws NullPointerException if either collection is null
+ * @see Collection#addAll
*/
- public static <E> E extractSingleton(final Collection<E> collection) {
- Objects.requireNonNull(collection, "collection");
- if (collection.size() != 1) {
- throw new IllegalArgumentException("Can extract singleton only when collection size == 1");
+ public static <O> Collection<O> union(final Iterable<? extends O> a, final Iterable<? extends O> b) {
+ Objects.requireNonNull(a, "a");
+ Objects.requireNonNull(b, "b");
+ final SetOperationCardinalityHelper<O> helper = new SetOperationCardinalityHelper<>(a, b);
+ for (final O obj : helper) {
+ helper.setCardinality(obj, helper.max(obj));
}
- return collection.iterator().next();
+ return helper.list();
+ }
+
+ /**
+ * Returns an unmodifiable collection backed by the given collection.
+ * <p>
+ * This method uses the implementation in the decorators subpackage.
+ * </p>
+ *
+ * @param <C> the type of object the {@link Collection} contains
+ * @param collection the collection to make unmodifiable, must not be null
+ * @return an unmodifiable collection backed by the given collection
+ * @throws NullPointerException if the collection is null
+ * @deprecated since 4.1, use {@link java.util.Collections#unmodifiableCollection(Collection)} instead
+ */
+ @Deprecated
+ public static <C> Collection<C> unmodifiableCollection(final Collection<? extends C> collection) {
+ Objects.requireNonNull(collection, "collection");
+ return UnmodifiableCollection.unmodifiableCollection(collection);
}
+
+ /**
+ * Don't allow instances.
+ */
+ private CollectionUtils() {}
}
diff --git a/src/main/java/org/apache/commons/collections4/ComparatorUtils.java b/src/main/java/org/apache/commons/collections4/ComparatorUtils.java
index 600ef4eb1..826c3a361 100644
--- a/src/main/java/org/apache/commons/collections4/ComparatorUtils.java
+++ b/src/main/java/org/apache/commons/collections4/ComparatorUtils.java
@@ -44,11 +44,6 @@ public class ComparatorUtils {
@SuppressWarnings("rawtypes")
private static final Comparator[] EMPTY_COMPARATOR_ARRAY = {};
- /**
- * Don't allow instances.
- */
- private ComparatorUtils() {}
-
/**
* Comparator for natural sort order.
*
@@ -58,14 +53,38 @@ public class ComparatorUtils {
public static final Comparator NATURAL_COMPARATOR = ComparableComparator.<Comparable>comparableComparator();
/**
- * Gets a comparator that uses the natural order of the objects.
+ * Gets a Comparator that can sort Boolean objects.
+ * <p>
+ * The parameter specifies whether true or false is sorted first.
+ * </p>
+ * <p>
+ * The comparator throws NullPointerException if a null value is compared.
+ * </p>
+ *
+ * @param trueFirst when {@code true}, sort
+ * {@code true} {@link Boolean}s before
+ * {@code false} {@link Boolean}s.
+ * @return a comparator that sorts booleans
+ */
+ public static Comparator<Boolean> booleanComparator(final boolean trueFirst) {
+ return BooleanComparator.booleanComparator(trueFirst);
+ }
+
+ /**
+ * Gets a comparator that compares using a collection of {@link Comparator}s,
+ * applied in (default iterator) sequence until one returns not equal or the
+ * collection is exhausted.
*
* @param <E> the object type to compare
- * @return a comparator which uses natural order
+ * @param comparators the comparators to use, not null or empty or containing nulls
+ * @return a {@link ComparatorChain} formed from the input comparators
+ * @throws NullPointerException if comparators collection is null or contains a null
+ * @throws ClassCastException if the comparators collection contains the wrong object type
+ * @see ComparatorChain
*/
@SuppressWarnings("unchecked")
- public static <E extends Comparable<? super E>> Comparator<E> naturalComparator() {
- return NATURAL_COMPARATOR;
+ public static <E> Comparator<E> chainedComparator(final Collection<Comparator<E>> comparators) {
+ return chainedComparator(comparators.toArray(EMPTY_COMPARATOR_ARRAY));
}
/**
@@ -87,56 +106,60 @@ public class ComparatorUtils {
}
/**
- * Gets a comparator that compares using a collection of {@link Comparator}s,
- * applied in (default iterator) sequence until one returns not equal or the
- * collection is exhausted.
+ * Returns the largest of the given objects according to the given
+ * comparator, returning the second object if the comparator
+ * returns equal.
*
* @param <E> the object type to compare
- * @param comparators the comparators to use, not null or empty or containing nulls
- * @return a {@link ComparatorChain} formed from the input comparators
- * @throws NullPointerException if comparators collection is null or contains a null
- * @throws ClassCastException if the comparators collection contains the wrong object type
- * @see ComparatorChain
+ * @param o1 the first object to compare
+ * @param o2 the second object to compare
+ * @param comparator the sort order to use
+ * @return the larger of the two objects
*/
@SuppressWarnings("unchecked")
- public static <E> Comparator<E> chainedComparator(final Collection<Comparator<E>> comparators) {
- return chainedComparator(comparators.toArray(EMPTY_COMPARATOR_ARRAY));
+ public static <E> E max(final E o1, final E o2, Comparator<E> comparator) {
+ if (comparator == null) {
+ comparator = NATURAL_COMPARATOR;
+ }
+ final int c = comparator.compare(o1, o2);
+ return c > 0 ? o1 : o2;
}
/**
- * Gets a comparator that reverses the order of the given comparator.
+ * Returns the smallest of the given objects according to the given
+ * comparator, returning the second object if the comparator
+ * returns equal.
*
* @param <E> the object type to compare
- * @param comparator the comparator to reverse
- * @return a comparator that reverses the order of the input comparator
- * @see ReverseComparator
+ * @param o1 the first object to compare
+ * @param o2 the second object to compare
+ * @param comparator the sort order to use
+ * @return the smaller of the two objects
*/
- public static <E> Comparator<E> reversedComparator(final Comparator<E> comparator) {
- return new ReverseComparator<>(comparator);
+ @SuppressWarnings("unchecked")
+ public static <E> E min(final E o1, final E o2, Comparator<E> comparator) {
+ if (comparator == null) {
+ comparator = NATURAL_COMPARATOR;
+ }
+ final int c = comparator.compare(o1, o2);
+ return c < 0 ? o1 : o2;
}
/**
- * Gets a Comparator that can sort Boolean objects.
- * <p>
- * The parameter specifies whether true or false is sorted first.
- * </p>
- * <p>
- * The comparator throws NullPointerException if a null value is compared.
- * </p>
+ * Gets a comparator that uses the natural order of the objects.
*
- * @param trueFirst when {@code true}, sort
- * {@code true} {@link Boolean}s before
- * {@code false} {@link Boolean}s.
- * @return a comparator that sorts booleans
+ * @param <E> the object type to compare
+ * @return a comparator which uses natural order
*/
- public static Comparator<Boolean> booleanComparator(final boolean trueFirst) {
- return BooleanComparator.booleanComparator(trueFirst);
+ @SuppressWarnings("unchecked")
+ public static <E extends Comparable<? super E>> Comparator<E> naturalComparator() {
+ return NATURAL_COMPARATOR;
}
/**
* Gets a Comparator that controls the comparison of {@code null} values.
* <p>
- * The returned comparator will consider a null value to be less than
+ * The returned comparator will consider a null value to be greater than
* any nonnull value, and equal to any other null value. Two nonnull
* values will be evaluated with the given comparator.
* </p>
@@ -147,17 +170,17 @@ public class ComparatorUtils {
* @see NullComparator
*/
@SuppressWarnings("unchecked")
- public static <E> Comparator<E> nullLowComparator(Comparator<E> comparator) {
+ public static <E> Comparator<E> nullHighComparator(Comparator<E> comparator) {
if (comparator == null) {
comparator = NATURAL_COMPARATOR;
}
- return new NullComparator<>(comparator, false);
+ return new NullComparator<>(comparator, true);
}
/**
* Gets a Comparator that controls the comparison of {@code null} values.
* <p>
- * The returned comparator will consider a null value to be greater than
+ * The returned comparator will consider a null value to be less than
* any nonnull value, and equal to any other null value. Two nonnull
* values will be evaluated with the given comparator.
* </p>
@@ -168,11 +191,23 @@ public class ComparatorUtils {
* @see NullComparator
*/
@SuppressWarnings("unchecked")
- public static <E> Comparator<E> nullHighComparator(Comparator<E> comparator) {
+ public static <E> Comparator<E> nullLowComparator(Comparator<E> comparator) {
if (comparator == null) {
comparator = NATURAL_COMPARATOR;
}
- return new NullComparator<>(comparator, true);
+ return new NullComparator<>(comparator, false);
+ }
+
+ /**
+ * Gets a comparator that reverses the order of the given comparator.
+ *
+ * @param <E> the object type to compare
+ * @param comparator the comparator to reverse
+ * @return a comparator that reverses the order of the input comparator
+ * @see ReverseComparator
+ */
+ public static <E> Comparator<E> reversedComparator(final Comparator<E> comparator) {
+ return new ReverseComparator<>(comparator);
}
/**
@@ -201,43 +236,8 @@ public class ComparatorUtils {
}
/**
- * Returns the smallest of the given objects according to the given
- * comparator, returning the second object if the comparator
- * returns equal.
- *
- * @param <E> the object type to compare
- * @param o1 the first object to compare
- * @param o2 the second object to compare
- * @param comparator the sort order to use
- * @return the smaller of the two objects
- */
- @SuppressWarnings("unchecked")
- public static <E> E min(final E o1, final E o2, Comparator<E> comparator) {
- if (comparator == null) {
- comparator = NATURAL_COMPARATOR;
- }
- final int c = comparator.compare(o1, o2);
- return c < 0 ? o1 : o2;
- }
-
- /**
- * Returns the largest of the given objects according to the given
- * comparator, returning the second object if the comparator
- * returns equal.
- *
- * @param <E> the object type to compare
- * @param o1 the first object to compare
- * @param o2 the second object to compare
- * @param comparator the sort order to use
- * @return the larger of the two objects
+ * Don't allow instances.
*/
- @SuppressWarnings("unchecked")
- public static <E> E max(final E o1, final E o2, Comparator<E> comparator) {
- if (comparator == null) {
- comparator = NATURAL_COMPARATOR;
- }
- final int c = comparator.compare(o1, o2);
- return c > 0 ? o1 : o2;
- }
+ private ComparatorUtils() {}
}
diff --git a/src/main/java/org/apache/commons/collections4/EnumerationUtils.java b/src/main/java/org/apache/commons/collections4/EnumerationUtils.java
index 8f31c737a..2012c9f95 100644
--- a/src/main/java/org/apache/commons/collections4/EnumerationUtils.java
+++ b/src/main/java/org/apache/commons/collections4/EnumerationUtils.java
@@ -31,13 +31,6 @@ import org.apache.commons.collections4.iterators.IteratorIterable;
*/
public class EnumerationUtils {
- /**
- * Don't allow instances.
- */
- private EnumerationUtils() {
- // no instances.
- }
-
/**
* Creates an {@link Iterable} that wraps an {@link Enumeration}. The returned {@link Iterable} can be used for a
* single iteration.
@@ -109,4 +102,11 @@ public class EnumerationUtils {
return result;
}
+ /**
+ * Don't allow instances.
+ */
+ private EnumerationUtils() {
+ // no instances.
+ }
+
}
diff --git a/src/main/java/org/apache/commons/collections4/FactoryUtils.java b/src/main/java/org/apache/commons/collections4/FactoryUtils.java
index 0b0a0bdca..76c58ec2b 100644
--- a/src/main/java/org/apache/commons/collections4/FactoryUtils.java
+++ b/src/main/java/org/apache/commons/collections4/FactoryUtils.java
@@ -43,36 +43,6 @@ import org.apache.commons.collections4.functors.PrototypeFactory;
*/
public class FactoryUtils {
- /**
- * Don't allow instances.
- */
- private FactoryUtils() {}
-
- /**
- * Gets a Factory that always throws an exception.
- * This could be useful during testing as a placeholder.
- *
- * @see org.apache.commons.collections4.functors.ExceptionFactory
- *
- * @param <T> the type that the factory creates
- * @return the factory
- */
- public static <T> Factory<T> exceptionFactory() {
- return ExceptionFactory.<T>exceptionFactory();
- }
-
- /**
- * Gets a Factory that will return null each time the factory is used.
- * This could be useful during testing as a placeholder.
- *
- * @see org.apache.commons.collections4.functors.ConstantFactory
- * @param <T> the "type" of null object the factory should return.
- * @return the factory
- */
- public static <T> Factory<T> nullFactory() {
- return ConstantFactory.<T>constantFactory(null);
- }
-
/**
* Creates a Factory that will return the same object each time the factory
* is used. No check is made that the object is immutable. In general, only
@@ -90,26 +60,16 @@ public class FactoryUtils {
}
/**
- * Creates a Factory that will return a clone of the same prototype object
- * each time the factory is used. The prototype will be cloned using one of these
- * techniques (in order):
- *
- * <ul>
- * <li>public clone method</li>
- * <li>public copy constructor</li>
- * <li>serialization clone</li>
- * </ul>
+ * Gets a Factory that always throws an exception.
+ * This could be useful during testing as a placeholder.
*
- * @see org.apache.commons.collections4.functors.PrototypeFactory
+ * @see org.apache.commons.collections4.functors.ExceptionFactory
*
* @param <T> the type that the factory creates
- * @param prototype the object to clone each time in the factory
- * @return the {@code prototype} factory, or a {@link ConstantFactory#NULL_INSTANCE} if
- * the {@code prototype} is {@code null}
- * @throws IllegalArgumentException if the prototype cannot be cloned
+ * @return the factory
*/
- public static <T> Factory<T> prototypeFactory(final T prototype) {
- return PrototypeFactory.<T>prototypeFactory(prototype);
+ public static <T> Factory<T> exceptionFactory() {
+ return ExceptionFactory.<T>exceptionFactory();
}
/**
@@ -147,4 +107,44 @@ public class FactoryUtils {
return InstantiateFactory.instantiateFactory(classToInstantiate, paramTypes, args);
}
+ /**
+ * Gets a Factory that will return null each time the factory is used.
+ * This could be useful during testing as a placeholder.
+ *
+ * @see org.apache.commons.collections4.functors.ConstantFactory
+ * @param <T> the "type" of null object the factory should return.
+ * @return the factory
+ */
+ public static <T> Factory<T> nullFactory() {
+ return ConstantFactory.<T>constantFactory(null);
+ }
+
+ /**
+ * Creates a Factory that will return a clone of the same prototype object
+ * each time the factory is used. The prototype will be cloned using one of these
+ * techniques (in order):
+ *
+ * <ul>
+ * <li>public clone method</li>
+ * <li>public copy constructor</li>
+ * <li>serialization clone</li>
+ * </ul>
+ *
+ * @see org.apache.commons.collections4.functors.PrototypeFactory
+ *
+ * @param <T> the type that the factory creates
+ * @param prototype the object to clone each time in the factory
+ * @return the {@code prototype} factory, or a {@link ConstantFactory#NULL_INSTANCE} if
+ * the {@code prototype} is {@code null}
+ * @throws IllegalArgumentException if the prototype cannot be cloned
+ */
+ public static <T> Factory<T> prototypeFactory(final T prototype) {
+ return PrototypeFactory.<T>prototypeFactory(prototype);
+ }
+
+ /**
+ * Don't allow instances.
+ */
+ private FactoryUtils() {}
+
}
diff --git a/src/main/java/org/apache/commons/collections4/FluentIterable.java b/src/main/java/org/apache/commons/collections4/FluentIterable.java
index 7f6d6552a..4a7054eb4 100644
--- a/src/main/java/org/apache/commons/collections4/FluentIterable.java
+++ b/src/main/java/org/apache/commons/collections4/FluentIterable.java
@@ -67,9 +67,6 @@ import org.apache.commons.collections4.iterators.SingletonIterator;
*/
public class FluentIterable<E> implements Iterable<E> {
- /** A reference to the wrapped iterable. */
- private final Iterable<E> iterable;
-
/**
* Creates a new empty FluentIterable.
*
@@ -80,6 +77,27 @@ public class FluentIterable<E> implements Iterable<E> {
return IterableUtils.EMPTY_ITERABLE;
}
+ /**
+ * Constructs a new FluentIterable from the provided iterable. If the
+ * iterable is already an instance of FluentIterable, the instance
+ * will be returned instead.
+ * <p>
+ * The returned iterable's iterator supports {@code remove()} when the
+ * corresponding input iterator supports it.
+ *
+ * @param <T> the element type
+ * @param iterable the iterable to wrap into a FluentIterable, may not be null
+ * @return a new FluentIterable wrapping the provided iterable
+ * @throws NullPointerException if iterable is null
+ */
+ public static <T> FluentIterable<T> of(final Iterable<T> iterable) {
+ IterableUtils.checkNotNull(iterable);
+ if (iterable instanceof FluentIterable<?>) {
+ return (FluentIterable<T>) iterable;
+ }
+ return new FluentIterable<>(iterable);
+ }
+
/**
* Creates a new FluentIterable of the single provided element.
* <p>
@@ -106,26 +124,8 @@ public class FluentIterable<E> implements Iterable<E> {
return of(Arrays.asList(elements));
}
- /**
- * Constructs a new FluentIterable from the provided iterable. If the
- * iterable is already an instance of FluentIterable, the instance
- * will be returned instead.
- * <p>
- * The returned iterable's iterator supports {@code remove()} when the
- * corresponding input iterator supports it.
- *
- * @param <T> the element type
- * @param iterable the iterable to wrap into a FluentIterable, may not be null
- * @return a new FluentIterable wrapping the provided iterable
- * @throws NullPointerException if iterable is null
- */
- public static <T> FluentIterable<T> of(final Iterable<T> iterable) {
- IterableUtils.checkNotNull(iterable);
- if (iterable instanceof FluentIterable<?>) {
- return (FluentIterable<T>) iterable;
- }
- return new FluentIterable<>(iterable);
- }
+ /** A reference to the wrapped iterable. */
+ private final Iterable<E> iterable;
/**
* Don't allow instances.
@@ -142,6 +142,35 @@ public class FluentIterable<E> implements Iterable<E> {
this.iterable = iterable;
}
+ /**
+ * Checks if all elements contained in this iterable are matching the
+ * provided predicate.
+ * <p>
+ * A {@code null} or empty iterable returns true.
+ *
+ * @param predicate the predicate to use, may not be null
+ * @return true if all elements contained in this iterable match the predicate,
+ * false otherwise
+ * @throws NullPointerException if predicate is null
+ */
+ public boolean allMatch(final Predicate<? super E> predicate) {
+ return IterableUtils.matchesAll(iterable, predicate);
+ }
+
+ /**
+ * Checks if this iterable contains any element matching the provided predicate.
+ * <p>
+ * A {@code null} or empty iterable returns false.
+ *
+ * @param predicate the predicate to use, may not be null
+ * @return true if at least one element contained in this iterable matches the predicate,
+ * false otherwise
+ * @throws NullPointerException if predicate is null
+ */
+ public boolean anyMatch(final Predicate<? super E> predicate) {
+ return IterableUtils.matchesAny(iterable, predicate);
+ }
+
/**
* Returns a new FluentIterable whose iterator will first traverse
* the elements of the current iterable, followed by the provided
@@ -167,6 +196,16 @@ public class FluentIterable<E> implements Iterable<E> {
return of(IterableUtils.chainedIterable(iterable, other));
}
+ /**
+ * Returns an Enumeration that will enumerate all elements contained
+ * in this iterable.
+ *
+ * @return an Enumeration over the elements of this iterable
+ */
+ public Enumeration<E> asEnumeration() {
+ return IteratorUtils.asEnumeration(iterator());
+ }
+
/**
* Returns a new FluentIterable whose iterator will traverse the
* elements of the current and provided iterable in natural order.
@@ -215,6 +254,28 @@ public class FluentIterable<E> implements Iterable<E> {
return of(IterableUtils.collatedIterable(comparator, iterable, other));
}
+ /**
+ * Checks if the object is contained in this iterable.
+ *
+ * @param object the object to check
+ * @return true if the object is contained in this iterable, false otherwise
+ */
+ public boolean contains(final Object object) {
+ return IterableUtils.contains(iterable, object);
+ }
+
+ /**
+ * Traverses an iterator of this iterable and adds all elements
+ * to the provided collection.
+ *
+ * @param collection the collection to add the elements
+ * @throws NullPointerException if collection is null
+ */
+ public void copyInto(final Collection<? super E> collection) {
+ Objects.requireNonNull(collection, "collection");
+ CollectionUtils.addAll(collection, iterable);
+ }
+
/**
* This method fully traverses an iterator of this iterable and returns
* a new iterable with the same contents, but without any reference
@@ -244,6 +305,45 @@ public class FluentIterable<E> implements Iterable<E> {
return of(IterableUtils.filteredIterable(iterable, predicate));
}
+ /**
+ * Applies the closure to all elements contained in this iterable.
+ *
+ * @param closure the closure to apply to each element, may not be null
+ * @throws NullPointerException if closure is null
+ */
+ public void forEach(final Closure<? super E> closure) {
+ IterableUtils.forEach(iterable, closure);
+ }
+
+ /**
+ * Returns the element at the provided position in this iterable.
+ * In order to return the element, an iterator needs to be traversed
+ * up to the requested position.
+ *
+ * @param position the position of the element to return
+ * @return the element
+ * @throws IndexOutOfBoundsException if the provided position is outside the
+ * valid range of this iterable: [0, size)
+ */
+ public E get(final int position) {
+ return IterableUtils.get(iterable, position);
+ }
+
+ /**
+ * Checks if this iterable is empty.
+ *
+ * @return true if this iterable does not contain any elements, false otherwise
+ */
+ public boolean isEmpty() {
+ return IterableUtils.isEmpty(iterable);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public Iterator<E> iterator() {
+ return iterable.iterator();
+ }
+
/**
* Returns a new FluentIterable whose iterator will return at most
* the provided maximum number of elements from this iterable.
@@ -276,6 +376,16 @@ public class FluentIterable<E> implements Iterable<E> {
return of(IterableUtils.reversedIterable(iterable));
}
+ /**
+ * Returns the number of elements that are contained in this iterable.
+ * In order to determine the size, an iterator needs to be traversed.
+ *
+ * @return the size of this iterable
+ */
+ public int size() {
+ return IterableUtils.size(iterable);
+ }
+
/**
* Returns a new FluentIterable whose iterator will skip the first
* N elements from this iterable.
@@ -289,6 +399,36 @@ public class FluentIterable<E> implements Iterable<E> {
return of(IterableUtils.skippingIterable(iterable, elementsToSkip));
}
+ /**
+ * Returns an array containing all elements of this iterable by traversing
+ * its iterator.
+ *
+ * @param arrayClass the class of array to create
+ * @return an array of the iterable contents
+ * @throws ArrayStoreException if arrayClass is invalid
+ */
+ public E[] toArray(final Class<E> arrayClass) {
+ return IteratorUtils.toArray(iterator(), arrayClass);
+ }
+
+ /**
+ * Returns a mutable list containing all elements of this iterable
+ * by traversing its iterator.
+ * <p>
+ * The returned list is guaranteed to be mutable.
+ *
+ * @return a list of the iterable contents
+ */
+ public List<E> toList() {
+ return IterableUtils.toList(iterable);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public String toString() {
+ return IterableUtils.toString(iterable);
+ }
+
/**
* Returns a new FluentIterable whose iterator will return all elements
* of this iterable transformed by the provided transformer.
@@ -348,144 +488,4 @@ public class FluentIterable<E> implements Iterable<E> {
return of(IterableUtils.zippingIterable(iterable, others));
}
- /** {@inheritDoc} */
- @Override
- public Iterator<E> iterator() {
- return iterable.iterator();
- }
-
- /**
- * Returns an Enumeration that will enumerate all elements contained
- * in this iterable.
- *
- * @return an Enumeration over the elements of this iterable
- */
- public Enumeration<E> asEnumeration() {
- return IteratorUtils.asEnumeration(iterator());
- }
-
- /**
- * Checks if all elements contained in this iterable are matching the
- * provided predicate.
- * <p>
- * A {@code null} or empty iterable returns true.
- *
- * @param predicate the predicate to use, may not be null
- * @return true if all elements contained in this iterable match the predicate,
- * false otherwise
- * @throws NullPointerException if predicate is null
- */
- public boolean allMatch(final Predicate<? super E> predicate) {
- return IterableUtils.matchesAll(iterable, predicate);
- }
-
- /**
- * Checks if this iterable contains any element matching the provided predicate.
- * <p>
- * A {@code null} or empty iterable returns false.
- *
- * @param predicate the predicate to use, may not be null
- * @return true if at least one element contained in this iterable matches the predicate,
- * false otherwise
- * @throws NullPointerException if predicate is null
- */
- public boolean anyMatch(final Predicate<? super E> predicate) {
- return IterableUtils.matchesAny(iterable, predicate);
- }
-
- /**
- * Checks if this iterable is empty.
- *
- * @return true if this iterable does not contain any elements, false otherwise
- */
- public boolean isEmpty() {
- return IterableUtils.isEmpty(iterable);
- }
-
- /**
- * Checks if the object is contained in this iterable.
- *
- * @param object the object to check
- * @return true if the object is contained in this iterable, false otherwise
- */
- public boolean contains(final Object object) {
- return IterableUtils.contains(iterable, object);
- }
-
- /**
- * Applies the closure to all elements contained in this iterable.
- *
- * @param closure the closure to apply to each element, may not be null
- * @throws NullPointerException if closure is null
- */
- public void forEach(final Closure<? super E> closure) {
- IterableUtils.forEach(iterable, closure);
- }
-
- /**
- * Returns the element at the provided position in this iterable.
- * In order to return the element, an iterator needs to be traversed
- * up to the requested position.
- *
- * @param position the position of the element to return
- * @return the element
- * @throws IndexOutOfBoundsException if the provided position is outside the
- * valid range of this iterable: [0, size)
- */
- public E get(final int position) {
- return IterableUtils.get(iterable, position);
- }
-
- /**
- * Returns the number of elements that are contained in this iterable.
- * In order to determine the size, an iterator needs to be traversed.
- *
- * @return the size of this iterable
- */
- public int size() {
- return IterableUtils.size(iterable);
- }
-
- /**
- * Traverses an iterator of this iterable and adds all elements
- * to the provided collection.
- *
- * @param collection the collection to add the elements
- * @throws NullPointerException if collection is null
- */
- public void copyInto(final Collection<? super E> collection) {
- Objects.requireNonNull(collection, "collection");
- CollectionUtils.addAll(collection, iterable);
- }
-
- /**
- * Returns an array containing all elements of this iterable by traversing
- * its iterator.
- *
- * @param arrayClass the class of array to create
- * @return an array of the iterable contents
- * @throws ArrayStoreException if arrayClass is invalid
- */
- public E[] toArray(final Class<E> arrayClass) {
- return IteratorUtils.toArray(iterator(), arrayClass);
- }
-
- /**
- * Returns a mutable list containing all elements of this iterable
- * by traversing its iterator.
- * <p>
- * The returned list is guaranteed to be mutable.
- *
- * @return a list of the iterable contents
- */
- public List<E> toList() {
- return IterableUtils.toList(iterable);
- }
-
- /** {@inheritDoc} */
- @Override
- public String toString() {
- return IterableUtils.toString(iterable);
- }
-
}
diff --git a/src/main/java/org/apache/commons/collections4/FunctorException.java b/src/main/java/org/apache/commons/collections4/FunctorException.java
index c497c93bb..64fc0d4c5 100644
--- a/src/main/java/org/apache/commons/collections4/FunctorException.java
+++ b/src/main/java/org/apache/commons/collections4/FunctorException.java
@@ -46,25 +46,25 @@ public class FunctorException extends RuntimeException {
/**
* Constructs a new {@code FunctorException} with specified
- * nested {@code Throwable} root cause.
+ * detail message and nested {@code Throwable} root cause.
*
+ * @param msg the error message.
* @param rootCause the exception or error that caused this exception
* to be thrown.
*/
- public FunctorException(final Throwable rootCause) {
- super(rootCause);
+ public FunctorException(final String msg, final Throwable rootCause) {
+ super(msg, rootCause);
}
/**
* Constructs a new {@code FunctorException} with specified
- * detail message and nested {@code Throwable} root cause.
+ * nested {@code Throwable} root cause.
*
- * @param msg the error message.
* @param rootCause the exception or error that caused this exception
* to be thrown.
*/
- public FunctorException(final String msg, final Throwable rootCause) {
- super(msg, rootCause);
+ public FunctorException(final Throwable rootCause) {
+ super(rootCause);
}
}
diff --git a/src/main/java/org/apache/commons/collections4/Get.java b/src/main/java/org/apache/commons/collections4/Get.java
index 5c590e7dd..782ebf1d0 100644
--- a/src/main/java/org/apache/commons/collections4/Get.java
+++ b/src/main/java/org/apache/commons/collections4/Get.java
@@ -60,14 +60,6 @@ public interface Get<K, V> {
*/
V get(Object key);
- /**
- * @param key key whose mapping is to be removed from the map
- * @return the previous value associated with {@code key}, or
- * {@code null} if there was no mapping for {@code key}.
- * @see java.util.Map#remove(Object)
- */
- V remove(Object key);
-
/**
* @return {@code true} if this map contains no key-value mappings
* @see java.util.Map#isEmpty()
@@ -80,6 +72,14 @@ public interface Get<K, V> {
*/
Set<K> keySet();
+ /**
+ * @param key key whose mapping is to be removed from the map
+ * @return the previous value associated with {@code key}, or
+ * {@code null} if there was no mapping for {@code key}.
+ * @see java.util.Map#remove(Object)
+ */
+ V remove(Object key);
+
/**
* @return the number of key-value mappings in this map
* @see java.util.Map#size()
diff --git a/src/main/java/org/apache/commons/collections4/IterableUtils.java b/src/main/java/org/apache/commons/collections4/IterableUtils.java
index f924f9143..ba0042f0b 100644
--- a/src/main/java/org/apache/commons/collections4/IterableUtils.java
+++ b/src/main/java/org/apache/commons/collections4/IterableUtils.java
@@ -50,6 +50,22 @@ import org.apache.commons.collections4.iterators.UniqueFilterIterator;
*/
public class IterableUtils {
+ /**
+ * Inner class to distinguish unmodifiable instances.
+ */
+ private static final class UnmodifiableIterable<E> extends FluentIterable<E> {
+ private final Iterable<E> unmodifiable;
+
+ UnmodifiableIterable(final Iterable<E> iterable) {
+ this.unmodifiable = iterable;
+ }
+
+ @Override
+ public Iterator<E> iterator() {
+ return IteratorUtils.unmodifiableIterator(unmodifiable.iterator());
+ }
+ }
+
/**
* An empty iterable.
*/
@@ -62,16 +78,64 @@ public class IterableUtils {
};
/**
- * Gets an empty iterable.
+ * Returns a view of the given iterable that contains at most the given number
+ * of elements.
* <p>
- * This iterable does not contain any elements.
+ * The returned iterable's iterator supports {@code remove()} when the corresponding
+ * input iterator supports it.
*
* @param <E> the element type
- * @return an empty iterable
+ * @param iterable the iterable to limit, may not be null
+ * @param maxSize the maximum number of elements, must not be negative
+ * @return a bounded view on the specified iterable
+ * @throws IllegalArgumentException if maxSize is negative
+ * @throws NullPointerException if iterable is null
*/
- @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type
- public static <E> Iterable<E> emptyIterable() {
- return EMPTY_ITERABLE;
+ public static <E> Iterable<E> boundedIterable(final Iterable<E> iterable, final long maxSize) {
+ checkNotNull(iterable);
+ if (maxSize < 0) {
+ throw new IllegalArgumentException("MaxSize parameter must not be negative.");
+ }
+
+ return new FluentIterable<E>() {
+ @Override
+ public Iterator<E> iterator() {
+ return IteratorUtils.boundedIterator(iterable.iterator(), maxSize);
+ }
+ };
+ }
+
+ /**
+ * Combines the provided iterables into a single iterable.
+ * <p>
+ * The returned iterable has an iterator that traverses the elements in the order
+ * of the arguments, i.e. iterables[0], iterables[1], .... The source iterators
+ * are not polled until necessary.
+ * <p>
+ * The returned iterable's iterator supports {@code remove()} when the corresponding
+ * input iterator supports it.
+ *
+ * @param <E> the element type
+ * @param iterables the iterables to combine, may not be null
+ * @return a new iterable, combining the provided iterables
+ * @throws NullPointerException if either of the provided iterables is null
+ */
+ public static <E> Iterable<E> chainedIterable(final Iterable<? extends E>... iterables) {
+ checkNotNull(iterables);
+ return new FluentIterable<E>() {
+ @Override
+ public Iterator<E> iterator() {
+ return new LazyIteratorChain<E>() {
+ @Override
+ protected Iterator<? extends E> nextIterator(final int count) {
+ if (count > iterables.length) {
+ return null;
+ }
+ return iterables[count - 1].iterator();
+ }
+ };
+ }
+ };
}
/**
@@ -147,34 +211,52 @@ public class IterableUtils {
}
/**
- * Combines the provided iterables into a single iterable.
- * <p>
- * The returned iterable has an iterator that traverses the elements in the order
- * of the arguments, i.e. iterables[0], iterables[1], .... The source iterators
- * are not polled until necessary.
+ * Fail-fast check for null arguments.
+ *
+ * @param iterable the iterable to check
+ * @throws NullPointerException if iterable is null
+ */
+ static void checkNotNull(final Iterable<?> iterable) {
+ Objects.requireNonNull(iterable, "iterable");
+ }
+
+ /**
+ * Fail-fast check for null arguments.
+ *
+ * @param iterables the iterables to check
+ * @throws NullPointerException if the argument or any of its contents is null
+ */
+ static void checkNotNull(final Iterable<?>... iterables) {
+ Objects.requireNonNull(iterables, "iterables");
+ for (final Iterable<?> iterable : iterables) {
+ checkNotNull(iterable);
+ }
+ }
+
+ /**
+ * Combines the two provided iterables into an ordered iterable using the
+ * provided comparator. If the comparator is null, natural ordering will be
+ * used.
* <p>
- * The returned iterable's iterator supports {@code remove()} when the corresponding
- * input iterator supports it.
+ * The returned iterable's iterator supports {@code remove()} when the
+ * corresponding input iterator supports it.
*
* @param <E> the element type
- * @param iterables the iterables to combine, may not be null
- * @return a new iterable, combining the provided iterables
+ * @param comparator the comparator defining an ordering over the elements,
+ * may be null, in which case natural ordering will be used
+ * @param a the first iterable, may not be null
+ * @param b the second iterable, may not be null
+ * @return a filtered view on the specified iterable
* @throws NullPointerException if either of the provided iterables is null
*/
- public static <E> Iterable<E> chainedIterable(final Iterable<? extends E>... iterables) {
- checkNotNull(iterables);
+ public static <E> Iterable<E> collatedIterable(final Comparator<? super E> comparator,
+ final Iterable<? extends E> a,
+ final Iterable<? extends E> b) {
+ checkNotNull(a, b);
return new FluentIterable<E>() {
@Override
public Iterator<E> iterator() {
- return new LazyIteratorChain<E>() {
- @Override
- protected Iterator<? extends E> nextIterator(final int count) {
- if (count > iterables.length) {
- return null;
- }
- return iterables[count - 1].iterator();
- }
- };
+ return IteratorUtils.collatedIterator(comparator, a.iterator(), b.iterator());
}
};
}
@@ -204,31 +286,96 @@ public class IterableUtils {
}
/**
- * Combines the two provided iterables into an ordered iterable using the
- * provided comparator. If the comparator is null, natural ordering will be
- * used.
+ * Checks if the object is contained in the given iterable. Object equality
+ * is tested with an {@code equator} unlike {@link #contains(Iterable, Object)}
+ * which uses {@link Object#equals(Object)}.
* <p>
- * The returned iterable's iterator supports {@code remove()} when the
- * corresponding input iterator supports it.
+ * A {@code null} or empty iterable returns false.
+ * A {@code null} object will not be passed to the equator, instead a
+ * {@link org.apache.commons.collections4.functors.NullPredicate NullPredicate}
+ * will be used.
+ *
+ * @param <E> the type of object the {@link Iterable} contains
+ * @param iterable the iterable to check, may be null
+ * @param object the object to check
+ * @param equator the equator to use to check, may not be null
+ * @return true if the object is contained in the iterable, false otherwise
+ * @throws NullPointerException if equator is null
+ */
+ public static <E> boolean contains(final Iterable<? extends E> iterable, final E object,
+ final Equator<? super E> equator) {
+ Objects.requireNonNull(equator, "equator");
+ return matchesAny(iterable, EqualPredicate.equalPredicate(object, equator));
+ }
+
+ /**
+ * Checks if the object is contained in the given iterable.
+ * <p>
+ * A {@code null} or empty iterable returns false.
+ *
+ * @param <E> the type of object the {@link Iterable} contains
+ * @param iterable the iterable to check, may be null
+ * @param object the object to check
+ * @return true if the object is contained in the iterable, false otherwise
+ */
+ public static <E> boolean contains(final Iterable<E> iterable, final Object object) {
+ if (iterable instanceof Collection<?>) {
+ return ((Collection<E>) iterable).contains(object);
+ }
+ return IteratorUtils.contains(emptyIteratorIfNull(iterable), object);
+ }
+
+ /**
+ * Counts the number of elements in the input iterable that match the predicate.
+ * <p>
+ * A {@code null} iterable matches no elements.
+ *
+ * @param <E> the type of object the {@link Iterable} contains
+ * @param input the {@link Iterable} to get the input from, may be null
+ * @param predicate the predicate to use, may not be null
+ * @return the number of matches for the predicate in the collection
+ * @throws NullPointerException if predicate is null
+ */
+ public static <E> long countMatches(final Iterable<E> input, final Predicate<? super E> predicate) {
+ Objects.requireNonNull(predicate, "predicate");
+ return size(filteredIterable(emptyIfNull(input), predicate));
+ }
+
+ /**
+ * Returns an immutable empty iterable if the argument is null,
+ * or the argument itself otherwise.
*
* @param <E> the element type
- * @param comparator the comparator defining an ordering over the elements,
- * may be null, in which case natural ordering will be used
- * @param a the first iterable, may not be null
- * @param b the second iterable, may not be null
- * @return a filtered view on the specified iterable
- * @throws NullPointerException if either of the provided iterables is null
+ * @param iterable the iterable, may be null
+ * @return an empty iterable if the argument is null
*/
- public static <E> Iterable<E> collatedIterable(final Comparator<? super E> comparator,
- final Iterable<? extends E> a,
- final Iterable<? extends E> b) {
- checkNotNull(a, b);
- return new FluentIterable<E>() {
- @Override
- public Iterator<E> iterator() {
- return IteratorUtils.collatedIterator(comparator, a.iterator(), b.iterator());
- }
- };
+ public static <E> Iterable<E> emptyIfNull(final Iterable<E> iterable) {
+ return iterable == null ? IterableUtils.<E>emptyIterable() : iterable;
+ }
+
+ /**
+ * Gets an empty iterable.
+ * <p>
+ * This iterable does not contain any elements.
+ *
+ * @param <E> the element type
+ * @return an empty iterable
+ */
+ @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type
+ public static <E> Iterable<E> emptyIterable() {
+ return EMPTY_ITERABLE;
+ }
+
+ /**
+ * Returns an empty iterator if the argument is {@code null},
+ * or {@code iterable.iterator()} otherwise.
+ *
+ * @param <E> the element type
+ * @param iterable the iterable, possibly {@code null}
+ * @return an empty iterator if the argument is {@code null}
+ */
+ private static <E> Iterator<E> emptyIteratorIfNull(final Iterable<E> iterable) {
+ return iterable != null ? iterable.iterator() : IteratorUtils.<E>emptyIterator();
}
/**
@@ -257,436 +404,64 @@ public class IterableUtils {
}
/**
- * Returns a view of the given iterable that contains at most the given number
- * of elements.
+ * Finds the first element in the given iterable which matches the given predicate.
* <p>
- * The returned iterable's iterator supports {@code remove()} when the corresponding
- * input iterator supports it.
+ * A {@code null} or empty iterator returns null.
*
* @param <E> the element type
- * @param iterable the iterable to limit, may not be null
- * @param maxSize the maximum number of elements, must not be negative
- * @return a bounded view on the specified iterable
- * @throws IllegalArgumentException if maxSize is negative
- * @throws NullPointerException if iterable is null
- */
- public static <E> Iterable<E> boundedIterable(final Iterable<E> iterable, final long maxSize) {
- checkNotNull(iterable);
- if (maxSize < 0) {
- throw new IllegalArgumentException("MaxSize parameter must not be negative.");
- }
-
- return new FluentIterable<E>() {
- @Override
- public Iterator<E> iterator() {
- return IteratorUtils.boundedIterator(iterable.iterator(), maxSize);
- }
- };
- }
-
- /**
- * Returns a view of the given iterable which will cycle infinitely over
- * its elements.
- * <p>
- * The returned iterable's iterator supports {@code remove()} if
- * {@code iterable.iterator()} does. After {@code remove()} is called, subsequent
- * cycles omit the removed element, which is no longer in {@code iterable}. The
- * iterator's {@code hasNext()} method returns {@code true} until {@code iterable}
- * is empty.
- *
- * @param <E> the element type
- * @param iterable the iterable to loop, may not be null
- * @return a view of the iterable, providing an infinite loop over its elements
- * @throws NullPointerException if iterable is null
- */
- public static <E> Iterable<E> loopingIterable(final Iterable<E> iterable) {
- checkNotNull(iterable);
- return new FluentIterable<E>() {
- @Override
- public Iterator<E> iterator() {
- return new LazyIteratorChain<E>() {
- @Override
- protected Iterator<? extends E> nextIterator(final int count) {
- if (IterableUtils.isEmpty(iterable)) {
- return null;
- }
- return iterable.iterator();
- }
- };
- }
- };
- }
-
- /**
- * Returns a reversed view of the given iterable.
- * <p>
- * In case the provided iterable is a {@link List} instance, a
- * {@link ReverseListIterator} will be used to reverse the traversal
- * order, otherwise an intermediate {@link List} needs to be created.
- * <p>
- * The returned iterable's iterator supports {@code remove()} if the
- * provided iterable is a {@link List} instance.
- *
- * @param <E> the element type
- * @param iterable the iterable to use, may not be null
- * @return a reversed view of the specified iterable
- * @throws NullPointerException if iterable is null
- * @see ReverseListIterator
- */
- public static <E> Iterable<E> reversedIterable(final Iterable<E> iterable) {
- checkNotNull(iterable);
- return new FluentIterable<E>() {
- @Override
- public Iterator<E> iterator() {
- final List<E> list = iterable instanceof List<?> ?
- (List<E>) iterable :
- IteratorUtils.toList(iterable.iterator());
- return new ReverseListIterator<>(list);
- }
- };
- }
-
- /**
- * Returns a view of the given iterable that skips the first N elements.
- * <p>
- * The returned iterable's iterator supports {@code remove()} when the corresponding
- * input iterator supports it.
- *
- * @param <E> the element type
- * @param iterable the iterable to use, may not be null
- * @param elementsToSkip the number of elements to skip from the start, must not be negative
- * @return a view of the specified iterable, skipping the first N elements
- * @throws IllegalArgumentException if elementsToSkip is negative
- * @throws NullPointerException if iterable is null
- */
- public static <E> Iterable<E> skippingIterable(final Iterable<E> iterable, final long elementsToSkip) {
- checkNotNull(iterable);
- if (elementsToSkip < 0) {
- throw new IllegalArgumentException("ElementsToSkip parameter must not be negative.");
- }
-
- return new FluentIterable<E>() {
- @Override
- public Iterator<E> iterator() {
- return IteratorUtils.skippingIterator(iterable.iterator(), elementsToSkip);
- }
- };
- }
-
- /**
- * Returns a transformed view of the given iterable where all of its elements
- * have been transformed by the provided transformer.
- * <p>
- * The returned iterable's iterator supports {@code remove()} when the corresponding
- * input iterator supports it.
- *
- * @param <I> the input element type
- * @param <O> the output element type
- * @param iterable the iterable to transform, may not be null
- * @param transformer the transformer, must not be null
- * @return a transformed view of the specified iterable
- * @throws NullPointerException if either iterable or transformer is null
- */
- public static <I, O> Iterable<O> transformedIterable(final Iterable<I> iterable,
- final Transformer<? super I, ? extends O> transformer) {
- checkNotNull(iterable);
- Objects.requireNonNull(transformer, "transformer");
- return new FluentIterable<O>() {
- @Override
- public Iterator<O> iterator() {
- return IteratorUtils.transformedIterator(iterable.iterator(), transformer);
- }
- };
- }
-
- /**
- * Returns a unique view of the given iterable.
- * <p>
- * The returned iterable's iterator supports {@code remove()} when the
- * corresponding input iterator supports it. Calling {@code remove()}
- * will only remove a single element from the underlying iterator.
- *
- * @param <E> the element type
- * @param iterable the iterable to use, may not be null
- * @return a unique view of the specified iterable
- * @throws NullPointerException if iterable is null
- */
- public static <E> Iterable<E> uniqueIterable(final Iterable<E> iterable) {
- checkNotNull(iterable);
- return new FluentIterable<E>() {
- @Override
- public Iterator<E> iterator() {
- return new UniqueFilterIterator<>(iterable.iterator());
- }
- };
- }
-
- /**
- * Returns an unmodifiable view of the given iterable.
- * <p>
- * The returned iterable's iterator does not support {@code remove()}.
- *
- * @param <E> the element type
- * @param iterable the iterable to use, may not be null
- * @return an unmodifiable view of the specified iterable
- * @throws NullPointerException if iterable is null
- */
- public static <E> Iterable<E> unmodifiableIterable(final Iterable<E> iterable) {
- checkNotNull(iterable);
- if (iterable instanceof UnmodifiableIterable<?>) {
- return iterable;
- }
- return new UnmodifiableIterable<>(iterable);
- }
-
- /**
- * Inner class to distinguish unmodifiable instances.
- */
- private static final class UnmodifiableIterable<E> extends FluentIterable<E> {
- private final Iterable<E> unmodifiable;
-
- UnmodifiableIterable(final Iterable<E> iterable) {
- this.unmodifiable = iterable;
- }
-
- @Override
- public Iterator<E> iterator() {
- return IteratorUtils.unmodifiableIterator(unmodifiable.iterator());
- }
- }
-
- /**
- * Interleaves two iterables into a single iterable.
- * <p>
- * The returned iterable has an iterator that traverses the elements in {@code a}
- * and {@code b} in alternating order. The source iterators are not polled until
- * necessary.
- * <p>
- * The returned iterable's iterator supports {@code remove()} when the corresponding
- * input iterator supports it.
- *
- * @param <E> the element type
- * @param a the first iterable, may not be null
- * @param b the second iterable, may not be null
- * @return a new iterable, interleaving the provided iterables
- * @throws NullPointerException if either a or b is null
- */
- public static <E> Iterable<E> zippingIterable(final Iterable<? extends E> a,
- final Iterable<? extends E> b) {
- checkNotNull(a);
- checkNotNull(b);
- return new FluentIterable<E>() {
- @Override
- public Iterator<E> iterator() {
- return IteratorUtils.zippingIterator(a.iterator(), b.iterator());
- }
- };
- }
-
- /**
- * Interleaves two iterables into a single iterable.
- * <p>
- * The returned iterable has an iterator that traverses the elements in {@code a}
- * and {@code b} in alternating order. The source iterators are not polled until
- * necessary.
- * <p>
- * The returned iterable's iterator supports {@code remove()} when the corresponding
- * input iterator supports it.
- *
- * @param <E> the element type
- * @param first the first iterable, may not be null
- * @param others the array of iterables to interleave, may not be null
- * @return a new iterable, interleaving the provided iterables
- * @throws NullPointerException if either of the provided iterables is null
- */
- public static <E> Iterable<E> zippingIterable(final Iterable<? extends E> first,
- final Iterable<? extends E>... others) {
- checkNotNull(first);
- checkNotNull(others);
- return new FluentIterable<E>() {
- @Override
- public Iterator<E> iterator() {
- @SuppressWarnings("unchecked") // safe
- final
- Iterator<? extends E>[] iterators = new Iterator[others.length + 1];
- iterators[0] = first.iterator();
- for (int i = 0; i < others.length; i++) {
- iterators[i + 1] = others[i].iterator();
- }
- return IteratorUtils.zippingIterator(iterators);
- }
- };
- }
-
- /**
- * Returns an immutable empty iterable if the argument is null,
- * or the argument itself otherwise.
- *
- * @param <E> the element type
- * @param iterable the iterable, may be null
- * @return an empty iterable if the argument is null
- */
- public static <E> Iterable<E> emptyIfNull(final Iterable<E> iterable) {
- return iterable == null ? IterableUtils.<E>emptyIterable() : iterable;
- }
-
- /**
- * Applies the closure to each element of the provided iterable.
- *
- * @param <E> the element type
- * @param iterable the iterator to use, may be null
- * @param closure the closure to apply to each element, may not be null
- * @throws NullPointerException if closure is null
- */
- public static <E> void forEach(final Iterable<E> iterable, final Closure<? super E> closure) {
- IteratorUtils.forEach(emptyIteratorIfNull(iterable), closure);
- }
-
- /**
- * Executes the given closure on each but the last element in the iterable.
- * <p>
- * If the input iterable is null no change is made.
- *
- * @param <E> the type of object the {@link Iterable} contains
- * @param iterable the iterable to get the input from, may be null
- * @param closure the closure to perform, may not be null
- * @return the last element in the iterable, or null if iterable is null or empty
- */
- public static <E> E forEachButLast(final Iterable<E> iterable, final Closure<? super E> closure) {
- return IteratorUtils.forEachButLast(emptyIteratorIfNull(iterable), closure);
- }
-
- /**
- * Finds the first element in the given iterable which matches the given predicate.
- * <p>
- * A {@code null} or empty iterator returns null.
- *
- * @param <E> the element type
- * @param iterable the iterable to search, may be null
- * @param predicate the predicate to use, must not be null
- * @return the first element of the iterable which matches the predicate or null if none could be found
- * @throws NullPointerException if predicate is null
+ * @param iterable the iterable to search, may be null
+ * @param predicate the predicate to use, must not be null
+ * @return the first element of the iterable which matches the predicate or null if none could be found
+ * @throws NullPointerException if predicate is null
*/
public static <E> E find(final Iterable<E> iterable, final Predicate<? super E> predicate) {
return IteratorUtils.find(emptyIteratorIfNull(iterable), predicate);
}
/**
- * Returns the index of the first element in the specified iterable that
- * matches the given predicate.
- * <p>
- * A {@code null} or empty iterable returns -1.
- *
- * @param <E> the element type
- * @param iterable the iterable to search, may be null
- * @param predicate the predicate to use, must not be null
- * @return the index of the first element which matches the predicate or -1 if none matches
- * @throws NullPointerException if predicate is null
- */
- public static <E> int indexOf(final Iterable<E> iterable, final Predicate<? super E> predicate) {
- return IteratorUtils.indexOf(emptyIteratorIfNull(iterable), predicate);
- }
-
- /**
- * Answers true if a predicate is true for every element of an iterable.
- * <p>
- * A {@code null} or empty iterable returns true.
- *
- * @param <E> the type of object the {@link Iterable} contains
- * @param iterable the {@link Iterable} to use, may be null
- * @param predicate the predicate to use, may not be null
- * @return true if every element of the collection matches the predicate or if the
- * collection is empty, false otherwise
- * @throws NullPointerException if predicate is null
- */
- public static <E> boolean matchesAll(final Iterable<E> iterable, final Predicate<? super E> predicate) {
- return IteratorUtils.matchesAll(emptyIteratorIfNull(iterable), predicate);
- }
-
- /**
- * Answers true if a predicate is true for any element of the iterable.
- * <p>
- * A {@code null} or empty iterable returns false.
- *
- * @param <E> the type of object the {@link Iterable} contains
- * @param iterable the {@link Iterable} to use, may be null
- * @param predicate the predicate to use, may not be null
- * @return true if any element of the collection matches the predicate, false otherwise
- * @throws NullPointerException if predicate is null
- */
- public static <E> boolean matchesAny(final Iterable<E> iterable, final Predicate<? super E> predicate) {
- return IteratorUtils.matchesAny(emptyIteratorIfNull(iterable), predicate);
- }
-
- /**
- * Counts the number of elements in the input iterable that match the predicate.
+ * Shortcut for {@code get(iterator, 0)}.
* <p>
- * A {@code null} iterable matches no elements.
- *
- * @param <E> the type of object the {@link Iterable} contains
- * @param input the {@link Iterable} to get the input from, may be null
- * @param predicate the predicate to use, may not be null
- * @return the number of matches for the predicate in the collection
- * @throws NullPointerException if predicate is null
- */
- public static <E> long countMatches(final Iterable<E> input, final Predicate<? super E> predicate) {
- Objects.requireNonNull(predicate, "predicate");
- return size(filteredIterable(emptyIfNull(input), predicate));
- }
-
- /**
- * Answers true if the provided iterable is empty.
+ * Returns the {@code first} value in the {@code iterable}'s {@link Iterator}, throwing
+ * {@code IndexOutOfBoundsException} if there is no such element.
+ * </p>
* <p>
- * A {@code null} iterable returns true.
+ * If the {@link Iterable} is a {@link List}, then it will use {@link List#get(int)}.
+ * </p>
*
- * @param iterable the {@link Iterable to use}, may be null
- * @return true if the iterable is null or empty, false otherwise
+ * @param <T> the type of object in the {@link Iterable}.
+ * @param iterable the {@link Iterable} to get a value from, may be null
+ * @return the first object
+ * @throws IndexOutOfBoundsException if the request is invalid
+ * @since 4.2
*/
- public static boolean isEmpty(final Iterable<?> iterable) {
- if (iterable instanceof Collection<?>) {
- return ((Collection<?>) iterable).isEmpty();
- }
- return IteratorUtils.isEmpty(emptyIteratorIfNull(iterable));
+ public static <T> T first(final Iterable<T> iterable) {
+ return get(iterable, 0);
}
/**
- * Checks if the object is contained in the given iterable.
- * <p>
- * A {@code null} or empty iterable returns false.
+ * Applies the closure to each element of the provided iterable.
*
- * @param <E> the type of object the {@link Iterable} contains
- * @param iterable the iterable to check, may be null
- * @param object the object to check
- * @return true if the object is contained in the iterable, false otherwise
+ * @param <E> the element type
+ * @param iterable the iterator to use, may be null
+ * @param closure the closure to apply to each element, may not be null
+ * @throws NullPointerException if closure is null
*/
- public static <E> boolean contains(final Iterable<E> iterable, final Object object) {
- if (iterable instanceof Collection<?>) {
- return ((Collection<E>) iterable).contains(object);
- }
- return IteratorUtils.contains(emptyIteratorIfNull(iterable), object);
+ public static <E> void forEach(final Iterable<E> iterable, final Closure<? super E> closure) {
+ IteratorUtils.forEach(emptyIteratorIfNull(iterable), closure);
}
/**
- * Checks if the object is contained in the given iterable. Object equality
- * is tested with an {@code equator} unlike {@link #contains(Iterable, Object)}
- * which uses {@link Object#equals(Object)}.
+ * Executes the given closure on each but the last element in the iterable.
* <p>
- * A {@code null} or empty iterable returns false.
- * A {@code null} object will not be passed to the equator, instead a
- * {@link org.apache.commons.collections4.functors.NullPredicate NullPredicate}
- * will be used.
+ * If the input iterable is null no change is made.
*
* @param <E> the type of object the {@link Iterable} contains
- * @param iterable the iterable to check, may be null
- * @param object the object to check
- * @param equator the equator to use to check, may not be null
- * @return true if the object is contained in the iterable, false otherwise
- * @throws NullPointerException if equator is null
+ * @param iterable the iterable to get the input from, may be null
+ * @param closure the closure to perform, may not be null
+ * @return the last element in the iterable, or null if iterable is null or empty
*/
- public static <E> boolean contains(final Iterable<? extends E> iterable, final E object,
- final Equator<? super E> equator) {
- Objects.requireNonNull(equator, "equator");
- return matchesAny(iterable, EqualPredicate.equalPredicate(object, equator));
+ public static <E> E forEachButLast(final Iterable<E> iterable, final Closure<? super E> closure) {
+ return IteratorUtils.forEachButLast(emptyIteratorIfNull(iterable), closure);
}
/**
@@ -729,87 +504,107 @@ public class IterableUtils {
}
/**
- * Shortcut for {@code get(iterator, 0)}.
- * <p>
- * Returns the {@code first} value in the {@code iterable}'s {@link Iterator}, throwing
- * {@code IndexOutOfBoundsException} if there is no such element.
- * </p>
+ * Returns the index of the first element in the specified iterable that
+ * matches the given predicate.
* <p>
- * If the {@link Iterable} is a {@link List}, then it will use {@link List#get(int)}.
- * </p>
+ * A {@code null} or empty iterable returns -1.
*
- * @param <T> the type of object in the {@link Iterable}.
- * @param iterable the {@link Iterable} to get a value from, may be null
- * @return the first object
- * @throws IndexOutOfBoundsException if the request is invalid
- * @since 4.2
+ * @param <E> the element type
+ * @param iterable the iterable to search, may be null
+ * @param predicate the predicate to use, must not be null
+ * @return the index of the first element which matches the predicate or -1 if none matches
+ * @throws NullPointerException if predicate is null
*/
- public static <T> T first(final Iterable<T> iterable) {
- return get(iterable, 0);
+ public static <E> int indexOf(final Iterable<E> iterable, final Predicate<? super E> predicate) {
+ return IteratorUtils.indexOf(emptyIteratorIfNull(iterable), predicate);
}
/**
- * Returns the number of elements contained in the given iterator.
+ * Answers true if the provided iterable is empty.
* <p>
- * A {@code null} or empty iterator returns {@code 0}.
+ * A {@code null} iterable returns true.
*
- * @param iterable the iterable to check, may be null
- * @return the number of elements contained in the iterable
+ * @param iterable the {@link Iterable to use}, may be null
+ * @return true if the iterable is null or empty, false otherwise
*/
- public static int size(final Iterable<?> iterable) {
- if (iterable == null) {
- return 0;
- }
+ public static boolean isEmpty(final Iterable<?> iterable) {
if (iterable instanceof Collection<?>) {
- return ((Collection<?>) iterable).size();
+ return ((Collection<?>) iterable).isEmpty();
}
- return IteratorUtils.size(emptyIteratorIfNull(iterable));
+ return IteratorUtils.isEmpty(emptyIteratorIfNull(iterable));
}
/**
- * Partitions all elements from iterable into separate output collections,
- * based on the evaluation of the given predicate.
+ * Returns a view of the given iterable which will cycle infinitely over
+ * its elements.
* <p>
- * For each predicate, the result will contain a list holding all elements of the
- * input iterable matching the predicate. The last list will hold all elements
- * which didn't match any predicate:
- * <pre>
- * [C1, R] = partition(I, P1) with
- * I = input
- * P1 = first predicate
- * C1 = collection of elements matching P1
- * R = collection of elements rejected by all predicates
- * </pre>
+ * The returned iterable's iterator supports {@code remove()} if
+ * {@code iterable.iterator()} does. After {@code remove()} is called, subsequent
+ * cycles omit the removed element, which is no longer in {@code iterable}. The
+ * iterator's {@code hasNext()} method returns {@code true} until {@code iterable}
+ * is empty.
+ *
+ * @param <E> the element type
+ * @param iterable the iterable to loop, may not be null
+ * @return a view of the iterable, providing an infinite loop over its elements
+ * @throws NullPointerException if iterable is null
+ */
+ public static <E> Iterable<E> loopingIterable(final Iterable<E> iterable) {
+ checkNotNull(iterable);
+ return new FluentIterable<E>() {
+ @Override
+ public Iterator<E> iterator() {
+ return new LazyIteratorChain<E>() {
+ @Override
+ protected Iterator<? extends E> nextIterator(final int count) {
+ if (IterableUtils.isEmpty(iterable)) {
+ return null;
+ }
+ return iterable.iterator();
+ }
+ };
+ }
+ };
+ }
+
+ /**
+ * Answers true if a predicate is true for every element of an iterable.
* <p>
- * If the input iterable is {@code null}, the same is returned as for an
- * empty iterable.
+ * A {@code null} or empty iterable returns true.
+ *
+ * @param <E> the type of object the {@link Iterable} contains
+ * @param iterable the {@link Iterable} to use, may be null
+ * @param predicate the predicate to use, may not be null
+ * @return true if every element of the collection matches the predicate or if the
+ * collection is empty, false otherwise
+ * @throws NullPointerException if predicate is null
+ */
+ public static <E> boolean matchesAll(final Iterable<E> iterable, final Predicate<? super E> predicate) {
+ return IteratorUtils.matchesAll(emptyIteratorIfNull(iterable), predicate);
+ }
+
+ /**
+ * Answers true if a predicate is true for any element of the iterable.
* <p>
- * Example: for an input list [1, 2, 3, 4, 5] calling partition with a predicate [x < 3]
- * will result in the following output: [[1, 2], [3, 4, 5]].
+ * A {@code null} or empty iterable returns false.
*
- * @param <O> the type of object the {@link Iterable} contains
- * @param iterable the iterable to partition, may be null
+ * @param <E> the type of object the {@link Iterable} contains
+ * @param iterable the {@link Iterable} to use, may be null
* @param predicate the predicate to use, may not be null
- * @return a list containing the output collections
+ * @return true if any element of the collection matches the predicate, false otherwise
* @throws NullPointerException if predicate is null
*/
- public static <O> List<List<O>> partition(final Iterable<? extends O> iterable,
- final Predicate<? super O> predicate) {
- Objects.requireNonNull(predicate, "predicate");
- @SuppressWarnings({ "unchecked", "rawtypes" }) // safe
- final Factory<List<O>> factory = FactoryUtils.instantiateFactory((Class) ArrayList.class);
- @SuppressWarnings("unchecked") // safe
- final Predicate<? super O>[] predicates = new Predicate[] { predicate };
- return partition(iterable, factory, predicates);
+ public static <E> boolean matchesAny(final Iterable<E> iterable, final Predicate<? super E> predicate) {
+ return IteratorUtils.matchesAny(emptyIteratorIfNull(iterable), predicate);
}
/**
* Partitions all elements from iterable into separate output collections,
* based on the evaluation of the given predicates.
* <p>
- * For each predicate, the result will contain a list holding all elements of the
- * input iterable matching the predicate. The last list will hold all elements
- * which didn't match any predicate:
+ * For each predicate, the returned list will contain a collection holding
+ * all elements of the input iterable matching the predicate. The last collection
+ * contained in the list will hold all elements which didn't match any predicate:
* <pre>
* [C1, C2, R] = partition(I, P1, P2) with
* I = input
@@ -825,21 +620,107 @@ public class IterableUtils {
* <p>
* If the input iterable is {@code null}, the same is returned as for an
* empty iterable.
+ * If no predicates have been provided, all elements of the input collection
+ * will be added to the rejected collection.
* <p>
* Example: for an input list [1, 2, 3, 4, 5] calling partition with predicates [x < 3]
* and [x < 5] will result in the following output: [[1, 2], [3, 4], [5]].
*
* @param <O> the type of object the {@link Iterable} contains
+ * @param <R> the type of the output {@link Collection}
* @param iterable the collection to get the input from, may be null
+ * @param partitionFactory the factory used to create the output collections
* @param predicates the predicates to use, may not be null
* @return a list containing the output collections
* @throws NullPointerException if any predicate is null
*/
- public static <O> List<List<O>> partition(final Iterable<? extends O> iterable,
- final Predicate<? super O>... predicates) {
+ public static <O, R extends Collection<O>> List<R> partition(final Iterable<? extends O> iterable,
+ final Factory<R> partitionFactory, final Predicate<? super O>... predicates) {
+
+ if (iterable == null) {
+ final Iterable<O> empty = emptyIterable();
+ return partition(empty, partitionFactory, predicates);
+ }
+
+ Objects.requireNonNull(predicates, "predicates");
+
+ for (final Predicate<?> predicate : predicates) {
+ Objects.requireNonNull(predicate, "predicate");
+ }
+
+ if (predicates.length < 1) {
+ // return the entire input collection as a single partition
+ final R singlePartition = partitionFactory.create();
+ CollectionUtils.addAll(singlePartition, iterable);
+ return Collections.singletonList(singlePartition);
+ }
+
+ // create the empty partitions
+ final int numberOfPredicates = predicates.length;
+ final int numberOfPartitions = numberOfPredicates + 1;
+ final List<R> partitions = new ArrayList<>(numberOfPartitions);
+ for (int i = 0; i < numberOfPartitions; ++i) {
+ partitions.add(partitionFactory.create());
+ }
+
+ // for each element in inputCollection:
+ // find the first predicate that evaluates to true.
+ // if there is a predicate, add the element to the corresponding partition.
+ // if there is no predicate, add it to the last, catch-all partition.
+ for (final O element : iterable) {
+ boolean elementAssigned = false;
+ for (int i = 0; i < numberOfPredicates; ++i) {
+ if (predicates[i].evaluate(element)) {
+ partitions.get(i).add(element);
+ elementAssigned = true;
+ break;
+ }
+ }
+
+ if (!elementAssigned) {
+ // no predicates evaluated to true
+ // add element to last partition
+ partitions.get(numberOfPredicates).add(element);
+ }
+ }
+
+ return partitions;
+ }
+ /**
+ * Partitions all elements from iterable into separate output collections,
+ * based on the evaluation of the given predicate.
+ * <p>
+ * For each predicate, the result will contain a list holding all elements of the
+ * input iterable matching the predicate. The last list will hold all elements
+ * which didn't match any predicate:
+ * <pre>
+ * [C1, R] = partition(I, P1) with
+ * I = input
+ * P1 = first predicate
+ * C1 = collection of elements matching P1
+ * R = collection of elements rejected by all predicates
+ * </pre>
+ * <p>
+ * If the input iterable is {@code null}, the same is returned as for an
+ * empty iterable.
+ * <p>
+ * Example: for an input list [1, 2, 3, 4, 5] calling partition with a predicate [x < 3]
+ * will result in the following output: [[1, 2], [3, 4, 5]].
+ *
+ * @param <O> the type of object the {@link Iterable} contains
+ * @param iterable the iterable to partition, may be null
+ * @param predicate the predicate to use, may not be null
+ * @return a list containing the output collections
+ * @throws NullPointerException if predicate is null
+ */
+ public static <O> List<List<O>> partition(final Iterable<? extends O> iterable,
+ final Predicate<? super O> predicate) {
+ Objects.requireNonNull(predicate, "predicate");
@SuppressWarnings({ "unchecked", "rawtypes" }) // safe
final Factory<List<O>> factory = FactoryUtils.instantiateFactory((Class) ArrayList.class);
+ @SuppressWarnings("unchecked") // safe
+ final Predicate<? super O>[] predicates = new Predicate[] { predicate };
return partition(iterable, factory, predicates);
}
@@ -847,9 +728,9 @@ public class IterableUtils {
* Partitions all elements from iterable into separate output collections,
* based on the evaluation of the given predicates.
* <p>
- * For each predicate, the returned list will contain a collection holding
- * all elements of the input iterable matching the predicate. The last collection
- * contained in the list will hold all elements which didn't match any predicate:
+ * For each predicate, the result will contain a list holding all elements of the
+ * input iterable matching the predicate. The last list will hold all elements
+ * which didn't match any predicate:
* <pre>
* [C1, C2, R] = partition(I, P1, P2) with
* I = input
@@ -865,71 +746,96 @@ public class IterableUtils {
* <p>
* If the input iterable is {@code null}, the same is returned as for an
* empty iterable.
- * If no predicates have been provided, all elements of the input collection
- * will be added to the rejected collection.
* <p>
* Example: for an input list [1, 2, 3, 4, 5] calling partition with predicates [x < 3]
* and [x < 5] will result in the following output: [[1, 2], [3, 4], [5]].
*
* @param <O> the type of object the {@link Iterable} contains
- * @param <R> the type of the output {@link Collection}
* @param iterable the collection to get the input from, may be null
- * @param partitionFactory the factory used to create the output collections
* @param predicates the predicates to use, may not be null
* @return a list containing the output collections
* @throws NullPointerException if any predicate is null
*/
- public static <O, R extends Collection<O>> List<R> partition(final Iterable<? extends O> iterable,
- final Factory<R> partitionFactory, final Predicate<? super O>... predicates) {
+ public static <O> List<List<O>> partition(final Iterable<? extends O> iterable,
+ final Predicate<? super O>... predicates) {
- if (iterable == null) {
- final Iterable<O> empty = emptyIterable();
- return partition(empty, partitionFactory, predicates);
- }
+ @SuppressWarnings({ "unchecked", "rawtypes" }) // safe
+ final Factory<List<O>> factory = FactoryUtils.instantiateFactory((Class) ArrayList.class);
+ return partition(iterable, factory, predicates);
+ }
- Objects.requireNonNull(predicates, "predicates");
+ /**
+ * Returns a reversed view of the given iterable.
+ * <p>
+ * In case the provided iterable is a {@link List} instance, a
+ * {@link ReverseListIterator} will be used to reverse the traversal
+ * order, otherwise an intermediate {@link List} needs to be created.
+ * <p>
+ * The returned iterable's iterator supports {@code remove()} if the
+ * provided iterable is a {@link List} instance.
+ *
+ * @param <E> the element type
+ * @param iterable the iterable to use, may not be null
+ * @return a reversed view of the specified iterable
+ * @throws NullPointerException if iterable is null
+ * @see ReverseListIterator
+ */
+ public static <E> Iterable<E> reversedIterable(final Iterable<E> iterable) {
+ checkNotNull(iterable);
+ return new FluentIterable<E>() {
+ @Override
+ public Iterator<E> iterator() {
+ final List<E> list = iterable instanceof List<?> ?
+ (List<E>) iterable :
+ IteratorUtils.toList(iterable.iterator());
+ return new ReverseListIterator<>(list);
+ }
+ };
+ }
- for (final Predicate<?> predicate : predicates) {
- Objects.requireNonNull(predicate, "predicate");
+ /**
+ * Returns the number of elements contained in the given iterator.
+ * <p>
+ * A {@code null} or empty iterator returns {@code 0}.
+ *
+ * @param iterable the iterable to check, may be null
+ * @return the number of elements contained in the iterable
+ */
+ public static int size(final Iterable<?> iterable) {
+ if (iterable == null) {
+ return 0;
}
-
- if (predicates.length < 1) {
- // return the entire input collection as a single partition
- final R singlePartition = partitionFactory.create();
- CollectionUtils.addAll(singlePartition, iterable);
- return Collections.singletonList(singlePartition);
+ if (iterable instanceof Collection<?>) {
+ return ((Collection<?>) iterable).size();
}
+ return IteratorUtils.size(emptyIteratorIfNull(iterable));
+ }
- // create the empty partitions
- final int numberOfPredicates = predicates.length;
- final int numberOfPartitions = numberOfPredicates + 1;
- final List<R> partitions = new ArrayList<>(numberOfPartitions);
- for (int i = 0; i < numberOfPartitions; ++i) {
- partitions.add(partitionFactory.create());
+ /**
+ * Returns a view of the given iterable that skips the first N elements.
+ * <p>
+ * The returned iterable's iterator supports {@code remove()} when the corresponding
+ * input iterator supports it.
+ *
+ * @param <E> the element type
+ * @param iterable the iterable to use, may not be null
+ * @param elementsToSkip the number of elements to skip from the start, must not be negative
+ * @return a view of the specified iterable, skipping the first N elements
+ * @throws IllegalArgumentException if elementsToSkip is negative
+ * @throws NullPointerException if iterable is null
+ */
+ public static <E> Iterable<E> skippingIterable(final Iterable<E> iterable, final long elementsToSkip) {
+ checkNotNull(iterable);
+ if (elementsToSkip < 0) {
+ throw new IllegalArgumentException("ElementsToSkip parameter must not be negative.");
}
- // for each element in inputCollection:
- // find the first predicate that evaluates to true.
- // if there is a predicate, add the element to the corresponding partition.
- // if there is no predicate, add it to the last, catch-all partition.
- for (final O element : iterable) {
- boolean elementAssigned = false;
- for (int i = 0; i < numberOfPredicates; ++i) {
- if (predicates[i].evaluate(element)) {
- partitions.get(i).add(element);
- elementAssigned = true;
- break;
- }
- }
-
- if (!elementAssigned) {
- // no predicates evaluated to true
- // add element to last partition
- partitions.get(numberOfPredicates).add(element);
+ return new FluentIterable<E>() {
+ @Override
+ public Iterator<E> iterator() {
+ return IteratorUtils.skippingIterator(iterable.iterator(), elementsToSkip);
}
- }
-
- return partitions;
+ };
}
/**
@@ -1006,38 +912,132 @@ public class IterableUtils {
}
/**
- * Fail-fast check for null arguments.
+ * Returns a transformed view of the given iterable where all of its elements
+ * have been transformed by the provided transformer.
+ * <p>
+ * The returned iterable's iterator supports {@code remove()} when the corresponding
+ * input iterator supports it.
*
- * @param iterable the iterable to check
+ * @param <I> the input element type
+ * @param <O> the output element type
+ * @param iterable the iterable to transform, may not be null
+ * @param transformer the transformer, must not be null
+ * @return a transformed view of the specified iterable
+ * @throws NullPointerException if either iterable or transformer is null
+ */
+ public static <I, O> Iterable<O> transformedIterable(final Iterable<I> iterable,
+ final Transformer<? super I, ? extends O> transformer) {
+ checkNotNull(iterable);
+ Objects.requireNonNull(transformer, "transformer");
+ return new FluentIterable<O>() {
+ @Override
+ public Iterator<O> iterator() {
+ return IteratorUtils.transformedIterator(iterable.iterator(), transformer);
+ }
+ };
+ }
+
+ /**
+ * Returns a unique view of the given iterable.
+ * <p>
+ * The returned iterable's iterator supports {@code remove()} when the
+ * corresponding input iterator supports it. Calling {@code remove()}
+ * will only remove a single element from the underlying iterator.
+ *
+ * @param <E> the element type
+ * @param iterable the iterable to use, may not be null
+ * @return a unique view of the specified iterable
* @throws NullPointerException if iterable is null
*/
- static void checkNotNull(final Iterable<?> iterable) {
- Objects.requireNonNull(iterable, "iterable");
+ public static <E> Iterable<E> uniqueIterable(final Iterable<E> iterable) {
+ checkNotNull(iterable);
+ return new FluentIterable<E>() {
+ @Override
+ public Iterator<E> iterator() {
+ return new UniqueFilterIterator<>(iterable.iterator());
+ }
+ };
}
/**
- * Fail-fast check for null arguments.
+ * Returns an unmodifiable view of the given iterable.
+ * <p>
+ * The returned iterable's iterator does not support {@code remove()}.
*
- * @param iterables the iterables to check
- * @throws NullPointerException if the argument or any of its contents is null
+ * @param <E> the element type
+ * @param iterable the iterable to use, may not be null
+ * @return an unmodifiable view of the specified iterable
+ * @throws NullPointerException if iterable is null
*/
- static void checkNotNull(final Iterable<?>... iterables) {
- Objects.requireNonNull(iterables, "iterables");
- for (final Iterable<?> iterable : iterables) {
- checkNotNull(iterable);
+ public static <E> Iterable<E> unmodifiableIterable(final Iterable<E> iterable) {
+ checkNotNull(iterable);
+ if (iterable instanceof UnmodifiableIterable<?>) {
+ return iterable;
}
+ return new UnmodifiableIterable<>(iterable);
}
/**
- * Returns an empty iterator if the argument is {@code null},
- * or {@code iterable.iterator()} otherwise.
+ * Interleaves two iterables into a single iterable.
+ * <p>
+ * The returned iterable has an iterator that traverses the elements in {@code a}
+ * and {@code b} in alternating order. The source iterators are not polled until
+ * necessary.
+ * <p>
+ * The returned iterable's iterator supports {@code remove()} when the corresponding
+ * input iterator supports it.
*
* @param <E> the element type
- * @param iterable the iterable, possibly {@code null}
- * @return an empty iterator if the argument is {@code null}
+ * @param a the first iterable, may not be null
+ * @param b the second iterable, may not be null
+ * @return a new iterable, interleaving the provided iterables
+ * @throws NullPointerException if either a or b is null
*/
- private static <E> Iterator<E> emptyIteratorIfNull(final Iterable<E> iterable) {
- return iterable != null ? iterable.iterator() : IteratorUtils.<E>emptyIterator();
+ public static <E> Iterable<E> zippingIterable(final Iterable<? extends E> a,
+ final Iterable<? extends E> b) {
+ checkNotNull(a);
+ checkNotNull(b);
+ return new FluentIterable<E>() {
+ @Override
+ public Iterator<E> iterator() {
+ return IteratorUtils.zippingIterator(a.iterator(), b.iterator());
+ }
+ };
+ }
+
+ /**
+ * Interleaves two iterables into a single iterable.
+ * <p>
+ * The returned iterable has an iterator that traverses the elements in {@code a}
+ * and {@code b} in alternating order. The source iterators are not polled until
+ * necessary.
+ * <p>
+ * The returned iterable's iterator supports {@code remove()} when the corresponding
+ * input iterator supports it.
+ *
+ * @param <E> the element type
+ * @param first the first iterable, may not be null
+ * @param others the array of iterables to interleave, may not be null
+ * @return a new iterable, interleaving the provided iterables
+ * @throws NullPointerException if either of the provided iterables is null
+ */
+ public static <E> Iterable<E> zippingIterable(final Iterable<? extends E> first,
+ final Iterable<? extends E>... others) {
+ checkNotNull(first);
+ checkNotNull(others);
+ return new FluentIterable<E>() {
+ @Override
+ public Iterator<E> iterator() {
+ @SuppressWarnings("unchecked") // safe
+ final
+ Iterator<? extends E>[] iterators = new Iterator[others.length + 1];
+ iterators[0] = first.iterator();
+ for (int i = 0; i < others.length; i++) {
+ iterators[i + 1] = others[i].iterator();
+ }
+ return IteratorUtils.zippingIterator(iterators);
+ }
+ };
}
}
diff --git a/src/main/java/org/apache/commons/collections4/IteratorUtils.java b/src/main/java/org/apache/commons/collections4/IteratorUtils.java
index 42c9a49f2..ecf5b21c5 100644
--- a/src/main/java/org/apache/commons/collections4/IteratorUtils.java
+++ b/src/main/java/org/apache/commons/collections4/IteratorUtils.java
@@ -110,118 +110,48 @@ public class IteratorUtils {
*/
private static final String DEFAULT_TOSTRING_DELIMITER = ", ";
+ // Arrays
/**
- * Don't allow instances.
- */
- private IteratorUtils() {}
-
- // Empty
- /**
- * Gets an empty iterator.
- * <p>
- * This iterator is a valid iterator object that will iterate over nothing.
- *
- * @param <E> the element type
- * @return an iterator over nothing
- */
- public static <E> ResettableIterator<E> emptyIterator() {
- return EmptyIterator.<E>resettableEmptyIterator();
- }
-
- /**
- * Gets an empty list iterator.
- * <p>
- * This iterator is a valid list iterator object that will iterate
- * over nothing.
- *
- * @param <E> the element type
- * @return a list iterator over nothing
- */
- public static <E> ResettableListIterator<E> emptyListIterator() {
- return EmptyListIterator.<E>resettableEmptyListIterator();
- }
-
- /**
- * Gets an empty ordered iterator.
- * <p>
- * This iterator is a valid iterator object that will iterate
- * over nothing.
- *
- * @param <E> the element type
- * @return an ordered iterator over nothing
- */
- public static <E> OrderedIterator<E> emptyOrderedIterator() {
- return EmptyOrderedIterator.<E>emptyOrderedIterator();
- }
-
- /**
- * Gets an empty map iterator.
- * <p>
- * This iterator is a valid map iterator object that will iterate
- * over nothing.
- *
- * @param <K> the key type
- * @param <V> the value type
- * @return a map iterator over nothing
- */
- public static <K, V> MapIterator<K, V> emptyMapIterator() {
- return EmptyMapIterator.<K, V>emptyMapIterator();
- }
-
- /**
- * Gets an empty ordered map iterator.
- * <p>
- * This iterator is a valid map iterator object that will iterate
- * over nothing.
- *
- * @param <K> the key type
- * @param <V> the value type
- * @return a map iterator over nothing
- */
- public static <K, V> OrderedMapIterator<K, V> emptyOrderedMapIterator() {
- return EmptyOrderedMapIterator.<K, V>emptyOrderedMapIterator();
- }
-
- // Singleton
- /**
- * Gets a singleton iterator.
- * <p>
- * This iterator is a valid iterator object that will iterate over
- * the specified object.
+ * Gets an iterator over an object array.
*
* @param <E> the element type
- * @param object the single object over which to iterate
- * @return a singleton iterator over the object
+ * @param array the array over which to iterate
+ * @return an iterator over the array
+ * @throws NullPointerException if array is null
*/
- public static <E> ResettableIterator<E> singletonIterator(final E object) {
- return new SingletonIterator<>(object);
+ public static <E> ResettableIterator<E> arrayIterator(final E... array) {
+ return new ObjectArrayIterator<>(array);
}
/**
- * Gets a singleton list iterator.
- * <p>
- * This iterator is a valid list iterator object that will iterate over
- * the specified object.
+ * Gets an iterator over the end part of an object array.
*
* @param <E> the element type
- * @param object the single object over which to iterate
- * @return a singleton list iterator over the object
+ * @param array the array over which to iterate
+ * @param start the index to start iterating at
+ * @return an iterator over part of the array
+ * @throws IndexOutOfBoundsException if start is less than zero or greater
+ * than the length of the array
+ * @throws NullPointerException if array is null
*/
- public static <E> ListIterator<E> singletonListIterator(final E object) {
- return new SingletonListIterator<>(object);
+ public static <E> ResettableIterator<E> arrayIterator(final E[] array, final int start) {
+ return new ObjectArrayIterator<>(array, start);
}
- // Arrays
/**
- * Gets an iterator over an object array.
+ * Gets an iterator over part of an object array.
*
* @param <E> the element type
* @param array the array over which to iterate
- * @return an iterator over the array
+ * @param start the index to start iterating at
+ * @param end the index to finish iterating at
+ * @return an iterator over part of the array
+ * @throws IndexOutOfBoundsException if array bounds are invalid
+ * @throws IllegalArgumentException if end is before start
* @throws NullPointerException if array is null
*/
- public static <E> ResettableIterator<E> arrayIterator(final E... array) {
- return new ObjectArrayIterator<>(array);
+ public static <E> ResettableIterator<E> arrayIterator(final E[] array, final int start, final int end) {
+ return new ObjectArrayIterator<>(array, start, end);
}
/**
@@ -240,21 +170,6 @@ public class IteratorUtils {
return new ArrayIterator<>(array);
}
- /**
- * Gets an iterator over the end part of an object array.
- *
- * @param <E> the element type
- * @param array the array over which to iterate
- * @param start the index to start iterating at
- * @return an iterator over part of the array
- * @throws IndexOutOfBoundsException if start is less than zero or greater
- * than the length of the array
- * @throws NullPointerException if array is null
- */
- public static <E> ResettableIterator<E> arrayIterator(final E[] array, final int start) {
- return new ObjectArrayIterator<>(array, start);
- }
-
/**
* Gets an iterator over the end part of an object or primitive array.
* <p>
@@ -274,22 +189,6 @@ public class IteratorUtils {
return new ArrayIterator<>(array, start);
}
- /**
- * Gets an iterator over part of an object array.
- *
- * @param <E> the element type
- * @param array the array over which to iterate
- * @param start the index to start iterating at
- * @param end the index to finish iterating at
- * @return an iterator over part of the array
- * @throws IndexOutOfBoundsException if array bounds are invalid
- * @throws IllegalArgumentException if end is before start
- * @throws NullPointerException if array is null
- */
- public static <E> ResettableIterator<E> arrayIterator(final E[] array, final int start, final int end) {
- return new ObjectArrayIterator<>(array, start, end);
- }
-
/**
* Gets an iterator over part of an object or primitive array.
* <p>
@@ -322,67 +221,67 @@ public class IteratorUtils {
}
/**
- * Gets a list iterator over an object or primitive array.
- * <p>
- * This method will handle primitive arrays as well as object arrays.
- * The primitives will be wrapped in the appropriate wrapper class.
+ * Gets a list iterator over the end part of an object array.
*
* @param <E> the element type
* @param array the array over which to iterate
- * @return a list iterator over the array
- * @throws IllegalArgumentException if the array is not an array
+ * @param start the index to start iterating at
+ * @return a list iterator over part of the array
+ * @throws IndexOutOfBoundsException if start is less than zero
* @throws NullPointerException if array is null
*/
- public static <E> ResettableListIterator<E> arrayListIterator(final Object array) {
- return new ArrayListIterator<>(array);
+ public static <E> ResettableListIterator<E> arrayListIterator(final E[] array, final int start) {
+ return new ObjectArrayListIterator<>(array, start);
}
/**
- * Gets a list iterator over the end part of an object array.
+ * Gets a list iterator over part of an object array.
*
* @param <E> the element type
* @param array the array over which to iterate
* @param start the index to start iterating at
+ * @param end the index to finish iterating at
* @return a list iterator over part of the array
- * @throws IndexOutOfBoundsException if start is less than zero
+ * @throws IndexOutOfBoundsException if array bounds are invalid
+ * @throws IllegalArgumentException if end is before start
* @throws NullPointerException if array is null
*/
- public static <E> ResettableListIterator<E> arrayListIterator(final E[] array, final int start) {
- return new ObjectArrayListIterator<>(array, start);
+ public static <E> ResettableListIterator<E> arrayListIterator(final E[] array, final int start, final int end) {
+ return new ObjectArrayListIterator<>(array, start, end);
}
/**
- * Gets a list iterator over the end part of an object or primitive array.
+ * Gets a list iterator over an object or primitive array.
* <p>
* This method will handle primitive arrays as well as object arrays.
* The primitives will be wrapped in the appropriate wrapper class.
*
* @param <E> the element type
* @param array the array over which to iterate
- * @param start the index to start iterating at
- * @return a list iterator over part of the array
+ * @return a list iterator over the array
* @throws IllegalArgumentException if the array is not an array
- * @throws IndexOutOfBoundsException if start is less than zero
* @throws NullPointerException if array is null
*/
- public static <E> ResettableListIterator<E> arrayListIterator(final Object array, final int start) {
- return new ArrayListIterator<>(array, start);
+ public static <E> ResettableListIterator<E> arrayListIterator(final Object array) {
+ return new ArrayListIterator<>(array);
}
/**
- * Gets a list iterator over part of an object array.
+ * Gets a list iterator over the end part of an object or primitive array.
+ * <p>
+ * This method will handle primitive arrays as well as object arrays.
+ * The primitives will be wrapped in the appropriate wrapper class.
*
* @param <E> the element type
* @param array the array over which to iterate
* @param start the index to start iterating at
- * @param end the index to finish iterating at
* @return a list iterator over part of the array
- * @throws IndexOutOfBoundsException if array bounds are invalid
- * @throws IllegalArgumentException if end is before start
+ * @throws IllegalArgumentException if the array is not an array
+ * @throws IndexOutOfBoundsException if start is less than zero
* @throws NullPointerException if array is null
*/
- public static <E> ResettableListIterator<E> arrayListIterator(final E[] array, final int start, final int end) {
- return new ObjectArrayListIterator<>(array, start, end);
+ public static <E> ResettableListIterator<E> arrayListIterator(final Object array, final int start) {
+ return new ArrayListIterator<>(array, start);
}
/**
@@ -404,104 +303,126 @@ public class IteratorUtils {
return new ArrayListIterator<>(array, start, end);
}
- // Bounded
/**
- * Decorates the specified iterator to return at most the given number
- * of elements.
+ * Gets an enumeration that wraps an iterator.
*
* @param <E> the element type
- * @param iterator the iterator to decorate
- * @param max the maximum number of elements returned by this iterator
- * @return a new bounded iterator
- * @throws NullPointerException if the iterator is null
- * @throws IllegalArgumentException if max is negative
- * @since 4.1
+ * @param iterator the iterator to use, may not be null
+ * @return a new enumeration
+ * @throws NullPointerException if iterator is null
*/
- public static <E> BoundedIterator<E> boundedIterator(final Iterator<? extends E> iterator, final long max) {
- return boundedIterator(iterator, 0, max);
+ public static <E> Enumeration<E> asEnumeration(final Iterator<? extends E> iterator) {
+ return new IteratorEnumeration<>(Objects.requireNonNull(iterator, "iterator"));
}
/**
- * Decorates the specified iterator to return at most the given number
- * of elements, skipping all elements until the iterator reaches the
- * position at {@code offset}.
- * <p>
- * The iterator is immediately advanced until it reaches the position at
- * {@code offset}, incurring O(n) time.
+ * Gets an {@link Iterable} that wraps an iterator. The returned {@link Iterable} can be
+ * used for a single iteration.
*
* @param <E> the element type
- * @param iterator the iterator to decorate
- * @param offset the index of the first element of the decorated iterator to return
- * @param max the maximum number of elements returned by this iterator
- * @return a new bounded iterator
- * @throws NullPointerException if the iterator is null
- * @throws IllegalArgumentException if either offset or max is negative
- * @since 4.1
+ * @param iterator the iterator to use, may not be null
+ * @return a new, single use {@link Iterable}
+ * @throws NullPointerException if iterator is null
*/
- public static <E> BoundedIterator<E> boundedIterator(final Iterator<? extends E> iterator,
- final long offset, final long max) {
- return new BoundedIterator<>(iterator, offset, max);
+ public static <E> Iterable<E> asIterable(final Iterator<? extends E> iterator) {
+ Objects.requireNonNull(iterator, "iterator");
+ return new IteratorIterable<>(iterator, false);
}
- // Unmodifiable
+ // Views
/**
- * Gets an immutable version of an {@link Iterator}. The returned object
- * will always throw an {@link UnsupportedOperationException} for
- * the {@link Iterator#remove} method.
+ * Gets an iterator that provides an iterator view of the given enumeration.
*
* @param <E> the element type
- * @param iterator the iterator to make immutable
- * @return an immutable version of the iterator
+ * @param enumeration the enumeration to use, may not be null
+ * @return a new iterator
+ * @throws NullPointerException if enumeration is null
*/
- public static <E> Iterator<E> unmodifiableIterator(final Iterator<E> iterator) {
- return UnmodifiableIterator.unmodifiableIterator(iterator);
+ public static <E> Iterator<E> asIterator(final Enumeration<? extends E> enumeration) {
+ return new EnumerationIterator<>(Objects.requireNonNull(enumeration, "enumeration"));
}
/**
- * Gets an immutable version of a {@link ListIterator}. The returned object
- * will always throw an {@link UnsupportedOperationException} for
- * the {@link Iterator#remove}, {@link ListIterator#add} and
- * {@link ListIterator#set} methods.
+ * Gets an iterator that provides an iterator view of the given enumeration
+ * that will remove elements from the specified collection.
*
* @param <E> the element type
- * @param listIterator the iterator to make immutable
- * @return an immutable version of the iterator
+ * @param enumeration the enumeration to use, may not be null
+ * @param removeCollection the collection to remove elements from, may not be null
+ * @return a new iterator
+ * @throws NullPointerException if enumeration or removeCollection is null
*/
- public static <E> ListIterator<E> unmodifiableListIterator(final ListIterator<E> listIterator) {
- return UnmodifiableListIterator.unmodifiableListIterator(listIterator);
+ public static <E> Iterator<E> asIterator(final Enumeration<? extends E> enumeration,
+ final Collection<? super E> removeCollection) {
+ return new EnumerationIterator<>(Objects.requireNonNull(enumeration, "enumeration"),
+ Objects.requireNonNull(removeCollection, "removeCollection"));
}
/**
- * Gets an immutable version of a {@link MapIterator}. The returned object
- * will always throw an {@link UnsupportedOperationException} for
- * the {@link Iterator#remove}, {@link MapIterator#setValue(Object)} methods.
+ * Gets an iterable that wraps an iterator. The returned iterable can be
+ * used for multiple iterations.
*
- * @param <K> the key type
- * @param <V> the value type
- * @param mapIterator the iterator to make immutable
- * @return an immutable version of the iterator
+ * @param <E> the element type
+ * @param iterator the iterator to use, may not be null
+ * @return a new, multiple use iterable
+ * @throws NullPointerException if iterator is null
*/
- public static <K, V> MapIterator<K, V> unmodifiableMapIterator(final MapIterator<K, V> mapIterator) {
- return UnmodifiableMapIterator.unmodifiableMapIterator(mapIterator);
+ public static <E> Iterable<E> asMultipleUseIterable(final Iterator<? extends E> iterator) {
+ Objects.requireNonNull(iterator, "iterator");
+ return new IteratorIterable<>(iterator, true);
}
- // Chained
+ // Bounded
+ /**
+ * Decorates the specified iterator to return at most the given number
+ * of elements.
+ *
+ * @param <E> the element type
+ * @param iterator the iterator to decorate
+ * @param max the maximum number of elements returned by this iterator
+ * @return a new bounded iterator
+ * @throws NullPointerException if the iterator is null
+ * @throws IllegalArgumentException if max is negative
+ * @since 4.1
+ */
+ public static <E> BoundedIterator<E> boundedIterator(final Iterator<? extends E> iterator, final long max) {
+ return boundedIterator(iterator, 0, max);
+ }
/**
- * Gets an iterator that iterates through two {@link Iterator}s
+ * Decorates the specified iterator to return at most the given number
+ * of elements, skipping all elements until the iterator reaches the
+ * position at {@code offset}.
+ * <p>
+ * The iterator is immediately advanced until it reaches the position at
+ * {@code offset}, incurring O(n) time.
+ *
+ * @param <E> the element type
+ * @param iterator the iterator to decorate
+ * @param offset the index of the first element of the decorated iterator to return
+ * @param max the maximum number of elements returned by this iterator
+ * @return a new bounded iterator
+ * @throws NullPointerException if the iterator is null
+ * @throws IllegalArgumentException if either offset or max is negative
+ * @since 4.1
+ */
+ public static <E> BoundedIterator<E> boundedIterator(final Iterator<? extends E> iterator,
+ final long offset, final long max) {
+ return new BoundedIterator<>(iterator, offset, max);
+ }
+
+ /**
+ * Gets an iterator that iterates through a collections of {@link Iterator}s
* one after another.
*
* @param <E> the element type
- * @param iterator1 the first iterator to use, not null
- * @param iterator2 the second iterator to use, not null
+ * @param iterators the iterators to use, not null or empty or contain nulls
* @return a combination iterator over the iterators
- * @throws NullPointerException if either iterator is null
+ * @throws NullPointerException if iterators collection is null or contains a null
+ * @throws ClassCastException if the iterators collection contains the wrong object type
*/
- public static <E> Iterator<E> chainedIterator(final Iterator<? extends E> iterator1,
- final Iterator<? extends E> iterator2) {
- // keep a version with two iterators to avoid the following warning in client code (Java 5 & 6)
- // "A generic array of E is created for a varargs parameter"
- return new IteratorChain<>(iterator1, iterator2);
+ public static <E> Iterator<E> chainedIterator(final Collection<Iterator<? extends E>> iterators) {
+ return new IteratorChain<>(iterators);
}
/**
@@ -518,44 +439,45 @@ public class IteratorUtils {
}
/**
- * Gets an iterator that iterates through a collections of {@link Iterator}s
+ * Gets an iterator that iterates through two {@link Iterator}s
* one after another.
*
* @param <E> the element type
- * @param iterators the iterators to use, not null or empty or contain nulls
+ * @param iterator1 the first iterator to use, not null
+ * @param iterator2 the second iterator to use, not null
* @return a combination iterator over the iterators
- * @throws NullPointerException if iterators collection is null or contains a null
- * @throws ClassCastException if the iterators collection contains the wrong object type
+ * @throws NullPointerException if either iterator is null
*/
- public static <E> Iterator<E> chainedIterator(final Collection<Iterator<? extends E>> iterators) {
- return new IteratorChain<>(iterators);
+ public static <E> Iterator<E> chainedIterator(final Iterator<? extends E> iterator1,
+ final Iterator<? extends E> iterator2) {
+ // keep a version with two iterators to avoid the following warning in client code (Java 5 & 6)
+ // "A generic array of E is created for a varargs parameter"
+ return new IteratorChain<>(iterator1, iterator2);
}
- // Collated
/**
* Gets an iterator that provides an ordered iteration over the elements
- * contained in a collection of ordered {@link Iterator}s.
+ * contained in a collection of {@link Iterator}s.
* <p>
* Given two ordered {@link Iterator}s {@code A} and {@code B},
* the {@link Iterator#next()} method will return the lesser of
- * {@code A.next()} and {@code B.next()}.
+ * {@code A.next()} and {@code B.next()} and so on.
* <p>
* The comparator is optional. If null is specified then natural order is used.
*
* @param <E> the element type
* @param comparator the comparator to use, may be null for natural order
- * @param iterator1 the first iterators to use, not null
- * @param iterator2 the first iterators to use, not null
+ * @param iterators the iterators to use, not null or empty or contain nulls
* @return a combination iterator over the iterators
- * @throws NullPointerException if either iterator is null
+ * @throws NullPointerException if iterators collection is null or contains a null
+ * @throws ClassCastException if the iterators collection contains the wrong object type
*/
public static <E> Iterator<E> collatedIterator(final Comparator<? super E> comparator,
- final Iterator<? extends E> iterator1,
- final Iterator<? extends E> iterator2) {
+ final Collection<Iterator<? extends E>> iterators) {
@SuppressWarnings("unchecked")
final Comparator<E> comp =
comparator == null ? ComparatorUtils.NATURAL_COMPARATOR : (Comparator<E>) comparator;
- return new CollatingIterator<>(comp, iterator1, iterator2);
+ return new CollatingIterator<>(comp, iterators);
}
/**
@@ -582,474 +504,275 @@ public class IteratorUtils {
return new CollatingIterator<>(comp, iterators);
}
+ // Collated
/**
* Gets an iterator that provides an ordered iteration over the elements
- * contained in a collection of {@link Iterator}s.
+ * contained in a collection of ordered {@link Iterator}s.
* <p>
* Given two ordered {@link Iterator}s {@code A} and {@code B},
* the {@link Iterator#next()} method will return the lesser of
- * {@code A.next()} and {@code B.next()} and so on.
+ * {@code A.next()} and {@code B.next()}.
* <p>
* The comparator is optional. If null is specified then natural order is used.
*
* @param <E> the element type
* @param comparator the comparator to use, may be null for natural order
- * @param iterators the iterators to use, not null or empty or contain nulls
+ * @param iterator1 the first iterators to use, not null
+ * @param iterator2 the first iterators to use, not null
* @return a combination iterator over the iterators
- * @throws NullPointerException if iterators collection is null or contains a null
- * @throws ClassCastException if the iterators collection contains the wrong object type
+ * @throws NullPointerException if either iterator is null
*/
public static <E> Iterator<E> collatedIterator(final Comparator<? super E> comparator,
- final Collection<Iterator<? extends E>> iterators) {
+ final Iterator<? extends E> iterator1,
+ final Iterator<? extends E> iterator2) {
@SuppressWarnings("unchecked")
final Comparator<E> comp =
comparator == null ? ComparatorUtils.NATURAL_COMPARATOR : (Comparator<E>) comparator;
- return new CollatingIterator<>(comp, iterators);
+ return new CollatingIterator<>(comp, iterator1, iterator2);
}
- // Object Graph
+ // Chained
+
/**
- * Gets an iterator that operates over an object graph.
- * <p>
- * This iterator can extract multiple objects from a complex tree-like object graph.
- * The iteration starts from a single root object.
- * It uses a {@code Transformer} to extract the iterators and elements.
- * Its main benefit is that no intermediate {@code List} is created.
- * <p>
- * For example, consider an object graph:
- * <pre>
- * |- Branch -- Leaf
- * | \- Leaf
- * |- Tree | /- Leaf
- * | |- Branch -- Leaf
- * Forest | \- Leaf
- * | |- Branch -- Leaf
- * | | \- Leaf
- * |- Tree | /- Leaf
- * |- Branch -- Leaf
- * |- Branch -- Leaf</pre>
- * The following {@code Transformer}, used in this class, will extract all
- * the Leaf objects without creating a combined intermediate list:
- * <pre>
- * public Object transform(Object input) {
- * if (input instanceof Forest) {
- * return ((Forest) input).treeIterator();
- * }
- * if (input instanceof Tree) {
- * return ((Tree) input).branchIterator();
- * }
- * if (input instanceof Branch) {
- * return ((Branch) input).leafIterator();
- * }
- * if (input instanceof Leaf) {
- * return input;
- * }
- * throw new ClassCastException();
- * }</pre>
- * <p>
- * Internally, iteration starts from the root object. When next is called,
- * the transformer is called to examine the object. The transformer will return
- * either an iterator or an object. If the object is an Iterator, the next element
- * from that iterator is obtained and the process repeats. If the element is an object
- * it is returned.
+ * Checks if the object is contained in the given iterator.
* <p>
- * Under many circumstances, linking Iterators together in this manner is
- * more efficient (and convenient) than using nested for loops to extract a list.
+ * A {@code null} or empty iterator returns false.
*
- * @param <E> the element type
- * @param root the root object to start iterating from, null results in an empty iterator
- * @param transformer the transformer to use, see above, null uses no effect transformer
- * @return a new object graph iterator
- * @since 3.1
+ * @param <E> the type of object the {@link Iterator} contains
+ * @param iterator the iterator to check, may be null
+ * @param object the object to check
+ * @return true if the object is contained in the iterator, false otherwise
+ * @since 4.1
*/
- public static <E> Iterator<E> objectGraphIterator(final E root,
- final Transformer<? super E, ? extends E> transformer) {
- return new ObjectGraphIterator<>(root, transformer);
+ public static <E> boolean contains(final Iterator<E> iterator, final Object object) {
+ return matchesAny(iterator, EqualPredicate.equalPredicate(object));
}
- // Transformed
+ // Empty
/**
- * Gets an iterator that transforms the elements of another iterator.
+ * Gets an empty iterator.
* <p>
- * The transformation occurs during the next() method and the underlying
- * iterator is unaffected by the transformation.
+ * This iterator is a valid iterator object that will iterate over nothing.
*
- * @param <I> the input type
- * @param <O> the output type
- * @param iterator the iterator to use, not null
- * @param transformer the transform to use, not null
- * @return a new transforming iterator
- * @throws NullPointerException if either parameter is null
+ * @param <E> the element type
+ * @return an iterator over nothing
*/
- public static <I, O> Iterator<O> transformedIterator(final Iterator<? extends I> iterator,
- final Transformer<? super I, ? extends O> transformer) {
-
- Objects.requireNonNull(iterator, "iterator");
- Objects.requireNonNull(transformer, "transformer");
- return new TransformIterator<>(iterator, transformer);
+ public static <E> ResettableIterator<E> emptyIterator() {
+ return EmptyIterator.<E>resettableEmptyIterator();
}
- // Filtered
/**
- * Gets an iterator that filters another iterator.
+ * Gets an empty list iterator.
* <p>
- * The returned iterator will only return objects that match the specified
- * filtering predicate.
+ * This iterator is a valid list iterator object that will iterate
+ * over nothing.
*
* @param <E> the element type
- * @param iterator the iterator to use, not null
- * @param predicate the predicate to use as a filter, not null
- * @return a new filtered iterator
- * @throws NullPointerException if either parameter is null
+ * @return a list iterator over nothing
*/
- public static <E> Iterator<E> filteredIterator(final Iterator<? extends E> iterator,
- final Predicate<? super E> predicate) {
- Objects.requireNonNull(iterator, "iterator");
- Objects.requireNonNull(predicate, "predicate");
- return new FilterIterator<>(iterator, predicate);
+ public static <E> ResettableListIterator<E> emptyListIterator() {
+ return EmptyListIterator.<E>resettableEmptyListIterator();
}
/**
- * Gets a list iterator that filters another list iterator.
+ * Gets an empty map iterator.
* <p>
- * The returned iterator will only return objects that match the specified
- * filtering predicate.
+ * This iterator is a valid map iterator object that will iterate
+ * over nothing.
*
- * @param <E> the element type
- * @param listIterator the list iterator to use, not null
- * @param predicate the predicate to use as a filter, not null
- * @return a new filtered iterator
- * @throws NullPointerException if either parameter is null
+ * @param <K> the key type
+ * @param <V> the value type
+ * @return a map iterator over nothing
*/
- public static <E> ListIterator<E> filteredListIterator(final ListIterator<? extends E> listIterator,
- final Predicate<? super E> predicate) {
-
- Objects.requireNonNull(listIterator, "listIterator");
- Objects.requireNonNull(predicate, "predicate");
- return new FilterListIterator<>(listIterator, predicate);
+ public static <K, V> MapIterator<K, V> emptyMapIterator() {
+ return EmptyMapIterator.<K, V>emptyMapIterator();
}
- // Looping
/**
- * Gets an iterator that loops continuously over the supplied collection.
+ * Gets an empty ordered iterator.
* <p>
- * The iterator will only stop looping if the remove method is called
- * enough times to empty the collection, or if the collection is empty
- * to start with.
+ * This iterator is a valid iterator object that will iterate
+ * over nothing.
*
* @param <E> the element type
- * @param collection the collection to iterate over, not null
- * @return a new looping iterator
- * @throws NullPointerException if the collection is null
+ * @return an ordered iterator over nothing
*/
- public static <E> ResettableIterator<E> loopingIterator(final Collection<? extends E> collection) {
- return new LoopingIterator<>(Objects.requireNonNull(collection, "collection"));
+ public static <E> OrderedIterator<E> emptyOrderedIterator() {
+ return EmptyOrderedIterator.<E>emptyOrderedIterator();
}
/**
- * Gets an iterator that loops continuously over the supplied list.
+ * Gets an empty ordered map iterator.
* <p>
- * The iterator will only stop looping if the remove method is called
- * enough times to empty the list, or if the list is empty to start with.
- *
- * @param <E> the element type
- * @param list the list to iterate over, not null
- * @return a new looping iterator
- * @throws NullPointerException if the list is null
- * @since 3.2
- */
- public static <E> ResettableListIterator<E> loopingListIterator(final List<E> list) {
- return new LoopingListIterator<>(Objects.requireNonNull(list, "list"));
- }
-
- // org.w3c.dom.NodeList iterators
- /**
- * Gets an {@link Iterator} that wraps the specified {@link NodeList}.
- * The returned {@link Iterator} can be used for a single iteration.
+ * This iterator is a valid map iterator object that will iterate
+ * over nothing.
*
- * @param nodeList the node list to use, may not be null
- * @return a new, single use {@link Iterator}
- * @throws NullPointerException if nodeList is null
- * @since 4.0
+ * @param <K> the key type
+ * @param <V> the value type
+ * @return a map iterator over nothing
*/
- public static NodeListIterator nodeListIterator(final NodeList nodeList) {
- return new NodeListIterator(Objects.requireNonNull(nodeList, "nodeList"));
+ public static <K, V> OrderedMapIterator<K, V> emptyOrderedMapIterator() {
+ return EmptyOrderedMapIterator.<K, V>emptyOrderedMapIterator();
}
+ // Filtered
/**
- * Gets an {@link Iterator} that wraps the specified node's childNodes.
- * The returned {@link Iterator} can be used for a single iteration.
+ * Gets an iterator that filters another iterator.
* <p>
- * Convenience method, allows easy iteration over NodeLists:
- * <pre>
- * Iterator<Node> iterator = IteratorUtils.nodeListIterator(node);
- * for (Node childNode : IteratorUtils.asIterable(iterator)) {
- * ...
- * }
- * </pre>
- *
- * @param node the node to use, may not be null
- * @return a new, single use {@link Iterator}
- * @throws NullPointerException if node is null
- * @since 4.0
- */
- public static NodeListIterator nodeListIterator(final Node node) {
- return new NodeListIterator(Objects.requireNonNull(node, "node"));
- }
-
- // Peeking
-
- /**
- * Gets an iterator that supports one-element lookahead.
- *
- * @param <E> the element type
- * @param iterator the iterator to decorate, not null
- * @return a peeking iterator
- * @throws NullPointerException if the iterator is null
- * @since 4.0
- */
- public static <E> Iterator<E> peekingIterator(final Iterator<? extends E> iterator) {
- return PeekingIterator.peekingIterator(iterator);
- }
-
- // Pushback
-
- /**
- * Gets an iterator that supports pushback of elements.
- *
- * @param <E> the element type
- * @param iterator the iterator to decorate, not null
- * @return a pushback iterator
- * @throws NullPointerException if the iterator is null
- * @since 4.0
- */
- public static <E> Iterator<E> pushbackIterator(final Iterator<? extends E> iterator) {
- return PushbackIterator.pushbackIterator(iterator);
- }
-
- // Skipping
- /**
- * Decorates the specified iterator to skip the first N elements.
+ * The returned iterator will only return objects that match the specified
+ * filtering predicate.
*
* @param <E> the element type
- * @param iterator the iterator to decorate
- * @param offset the first number of elements to skip
- * @return a new skipping iterator
- * @throws NullPointerException if the iterator is null
- * @throws IllegalArgumentException if offset is negative
- * @since 4.1
+ * @param iterator the iterator to use, not null
+ * @param predicate the predicate to use as a filter, not null
+ * @return a new filtered iterator
+ * @throws NullPointerException if either parameter is null
*/
- public static <E> SkippingIterator<E> skippingIterator(final Iterator<E> iterator, final long offset) {
- return new SkippingIterator<>(iterator, offset);
+ public static <E> Iterator<E> filteredIterator(final Iterator<? extends E> iterator,
+ final Predicate<? super E> predicate) {
+ Objects.requireNonNull(iterator, "iterator");
+ Objects.requireNonNull(predicate, "predicate");
+ return new FilterIterator<>(iterator, predicate);
}
- // Zipping
/**
- * Returns an iterator that interleaves elements from the decorated iterators.
+ * Gets a list iterator that filters another list iterator.
+ * <p>
+ * The returned iterator will only return objects that match the specified
+ * filtering predicate.
*
* @param <E> the element type
- * @param a the first iterator to interleave
- * @param b the second iterator to interleave
- * @return an iterator, interleaving the decorated iterators
- * @throws NullPointerException if any iterator is null
- * @since 4.1
+ * @param listIterator the list iterator to use, not null
+ * @param predicate the predicate to use as a filter, not null
+ * @return a new filtered iterator
+ * @throws NullPointerException if either parameter is null
*/
- public static <E> ZippingIterator<E> zippingIterator(final Iterator<? extends E> a,
- final Iterator<? extends E> b) {
- return new ZippingIterator<>(a, b);
- }
+ public static <E> ListIterator<E> filteredListIterator(final ListIterator<? extends E> listIterator,
+ final Predicate<? super E> predicate) {
- /**
- * Returns an iterator that interleaves elements from the decorated iterators.
- *
- * @param <E> the element type
- * @param a the first iterator to interleave
- * @param b the second iterator to interleave
- * @param c the third iterator to interleave
- * @return an iterator, interleaving the decorated iterators
- * @throws NullPointerException if any iterator is null
- * @since 4.1
- */
- public static <E> ZippingIterator<E> zippingIterator(final Iterator<? extends E> a,
- final Iterator<? extends E> b,
- final Iterator<? extends E> c) {
- return new ZippingIterator<>(a, b, c);
+ Objects.requireNonNull(listIterator, "listIterator");
+ Objects.requireNonNull(predicate, "predicate");
+ return new FilterListIterator<>(listIterator, predicate);
}
/**
- * Returns an iterator that interleaves elements from the decorated iterators.
+ * Finds the first element in the given iterator which matches the given predicate.
+ * <p>
+ * A {@code null} or empty iterator returns null.
*
* @param <E> the element type
- * @param iterators the array of iterators to interleave
- * @return an iterator, interleaving the decorated iterators
- * @throws NullPointerException if any iterator is null
+ * @param iterator the iterator to search, may be null
+ * @param predicate the predicate to use, must not be null
+ * @return the first element of the iterator which matches the predicate or null if none could be found
+ * @throws NullPointerException if predicate is null
* @since 4.1
*/
- public static <E> ZippingIterator<E> zippingIterator(final Iterator<? extends E>... iterators) {
- return new ZippingIterator<>(iterators);
- }
-
- // Views
- /**
- * Gets an iterator that provides an iterator view of the given enumeration.
- *
- * @param <E> the element type
- * @param enumeration the enumeration to use, may not be null
- * @return a new iterator
- * @throws NullPointerException if enumeration is null
- */
- public static <E> Iterator<E> asIterator(final Enumeration<? extends E> enumeration) {
- return new EnumerationIterator<>(Objects.requireNonNull(enumeration, "enumeration"));
- }
-
- /**
- * Gets an iterator that provides an iterator view of the given enumeration
- * that will remove elements from the specified collection.
- *
- * @param <E> the element type
- * @param enumeration the enumeration to use, may not be null
- * @param removeCollection the collection to remove elements from, may not be null
- * @return a new iterator
- * @throws NullPointerException if enumeration or removeCollection is null
- */
- public static <E> Iterator<E> asIterator(final Enumeration<? extends E> enumeration,
- final Collection<? super E> removeCollection) {
- return new EnumerationIterator<>(Objects.requireNonNull(enumeration, "enumeration"),
- Objects.requireNonNull(removeCollection, "removeCollection"));
- }
-
- /**
- * Gets an enumeration that wraps an iterator.
- *
- * @param <E> the element type
- * @param iterator the iterator to use, may not be null
- * @return a new enumeration
- * @throws NullPointerException if iterator is null
- */
- public static <E> Enumeration<E> asEnumeration(final Iterator<? extends E> iterator) {
- return new IteratorEnumeration<>(Objects.requireNonNull(iterator, "iterator"));
- }
-
- /**
- * Gets an {@link Iterable} that wraps an iterator. The returned {@link Iterable} can be
- * used for a single iteration.
- *
- * @param <E> the element type
- * @param iterator the iterator to use, may not be null
- * @return a new, single use {@link Iterable}
- * @throws NullPointerException if iterator is null
- */
- public static <E> Iterable<E> asIterable(final Iterator<? extends E> iterator) {
- Objects.requireNonNull(iterator, "iterator");
- return new IteratorIterable<>(iterator, false);
- }
+ public static <E> E find(final Iterator<E> iterator, final Predicate<? super E> predicate) {
+ Objects.requireNonNull(predicate, "predicate");
- /**
- * Gets an iterable that wraps an iterator. The returned iterable can be
- * used for multiple iterations.
- *
- * @param <E> the element type
- * @param iterator the iterator to use, may not be null
- * @return a new, multiple use iterable
- * @throws NullPointerException if iterator is null
- */
- public static <E> Iterable<E> asMultipleUseIterable(final Iterator<? extends E> iterator) {
- Objects.requireNonNull(iterator, "iterator");
- return new IteratorIterable<>(iterator, true);
+ if (iterator != null) {
+ while (iterator.hasNext()) {
+ final E element = iterator.next();
+ if (predicate.evaluate(element)) {
+ return element;
+ }
+ }
+ }
+ return null;
}
/**
- * Gets a list iterator based on a simple iterator.
+ * Shortcut for {@code get(iterator, 0)}.
* <p>
- * As the wrapped Iterator is traversed, a LinkedList of its values is
- * cached, permitting all required operations of ListIterator.
- *
- * @param <E> the element type
- * @param iterator the iterator to use, may not be null
- * @return a new iterator
- * @throws NullPointerException if iterator parameter is null
- */
- public static <E> ListIterator<E> toListIterator(final Iterator<? extends E> iterator) {
- Objects.requireNonNull(iterator, "iterator");
- return new ListIteratorWrapper<>(iterator);
- }
-
- /**
- * Gets an array based on an iterator.
+ * Returns the {@code first} value in {@link Iterator}, throwing
+ * {@code IndexOutOfBoundsException} if there is no such element.
+ * </p>
* <p>
- * As the wrapped Iterator is traversed, an ArrayList of its values is
- * created. At the end, this is converted to an array.
- *
- * @param iterator the iterator to use, not null
- * @return an array of the iterator contents
- * @throws NullPointerException if iterator parameter is null
+ * The Iterator is advanced to {@code 0} (or to the end, if
+ * {@code 0} exceeds the number of entries) as a side effect of this method.
+ * </p>
+ * @param <E> the type of object in the {@link Iterator}
+ * @param iterator the iterator to get a value from
+ * @return the first object
+ * @throws IndexOutOfBoundsException if the request is invalid
+ * @since 4.2
*/
- public static Object[] toArray(final Iterator<?> iterator) {
- Objects.requireNonNull(iterator, "iterator");
- final List<?> list = toList(iterator, 100);
- return list.toArray();
+ public static <E> E first(final Iterator<E> iterator) {
+ return get(iterator, 0);
}
/**
- * Gets an array based on an iterator.
- * <p>
- * As the wrapped Iterator is traversed, an ArrayList of its values is
- * created. At the end, this is converted to an array.
+ * Applies the closure to each element of the provided iterator.
*
* @param <E> the element type
- * @param iterator the iterator to use, not null
- * @param arrayClass the class of array to create
- * @return an array of the iterator contents
- * @throws NullPointerException if iterator parameter or arrayClass is null
- * @throws ArrayStoreException if the arrayClass is invalid
+ * @param iterator the iterator to use, may be null
+ * @param closure the closure to apply to each element, may not be null
+ * @throws NullPointerException if closure is null
+ * @since 4.1
*/
- public static <E> E[] toArray(final Iterator<? extends E> iterator, final Class<E> arrayClass) {
- Objects.requireNonNull(iterator, "iterator");
- Objects.requireNonNull(arrayClass, "arrayClass");
- final List<E> list = toList(iterator, 100);
- @SuppressWarnings("unchecked")
- final E[] array = (E[]) Array.newInstance(arrayClass, list.size());
- return list.toArray(array);
+ public static <E> void forEach(final Iterator<E> iterator, final Closure<? super E> closure) {
+ Objects.requireNonNull(closure, "closure");
+
+ if (iterator != null) {
+ while (iterator.hasNext()) {
+ final E element = iterator.next();
+ closure.execute(element);
+ }
+ }
}
/**
- * Gets a list based on an iterator.
+ * Executes the given closure on each but the last element in the iterator.
* <p>
- * As the wrapped Iterator is traversed, an ArrayList of its values is
- * created. At the end, the list is returned.
+ * If the input iterator is null no change is made.
*
- * @param <E> the element type
- * @param iterator the iterator to use, not null
- * @return a list of the iterator contents
- * @throws NullPointerException if iterator parameter is null
+ * @param <E> the type of object the {@link Iterator} contains
+ * @param iterator the iterator to get the input from, may be null
+ * @param closure the closure to perform, may not be null
+ * @return the last element in the iterator, or null if iterator is null or empty
+ * @throws NullPointerException if closure is null
+ * @since 4.1
*/
- public static <E> List<E> toList(final Iterator<? extends E> iterator) {
- return toList(iterator, 10);
+ public static <E> E forEachButLast(final Iterator<E> iterator, final Closure<? super E> closure) {
+ Objects.requireNonNull(closure, "closure");
+
+ if (iterator != null) {
+ while (iterator.hasNext()) {
+ final E element = iterator.next();
+ if (!iterator.hasNext()) {
+ return element;
+ }
+ closure.execute(element);
+ }
+ }
+ return null;
}
/**
- * Gets a list based on an iterator.
+ * Returns the {@code index}-th value in {@link Iterator}, throwing
+ * {@code IndexOutOfBoundsException} if there is no such element.
* <p>
- * As the wrapped Iterator is traversed, an ArrayList of its values is
- * created. At the end, the list is returned.
+ * The Iterator is advanced to {@code index} (or to the end, if
+ * {@code index} exceeds the number of entries) as a side effect of this method.
*
- * @param <E> the element type
- * @param iterator the iterator to use, not null
- * @param estimatedSize the initial size of the ArrayList
- * @return a list of the iterator contents
- * @throws NullPointerException if iterator parameter is null
- * @throws IllegalArgumentException if the size is less than 1
+ * @param <E> the type of object in the {@link Iterator}
+ * @param iterator the iterator to get a value from
+ * @param index the index to get
+ * @return the object at the specified index
+ * @throws IndexOutOfBoundsException if the index is invalid
+ * @since 4.1
*/
- public static <E> List<E> toList(final Iterator<? extends E> iterator, final int estimatedSize) {
- Objects.requireNonNull(iterator, "iterator");
- if (estimatedSize < 1) {
- throw new IllegalArgumentException("Estimated size must be greater than 0");
- }
- final List<E> list = new ArrayList<>(estimatedSize);
+ public static <E> E get(final Iterator<E> iterator, final int index) {
+ int i = index;
+ CollectionUtils.checkIndexBounds(i);
while (iterator.hasNext()) {
- list.add(iterator.next());
+ i--;
+ if (i == -1) {
+ return iterator.next();
+ }
+ iterator.next();
}
- return list;
+ throw new IndexOutOfBoundsException("Entry does not exist: " + i);
}
/**
@@ -1102,97 +825,24 @@ public class IteratorUtils {
return new EnumerationIterator<>(((Dictionary<?, ?>) obj).elements());
}
if (obj.getClass().isArray()) {
- return new ArrayIterator<>(obj);
- }
- try {
- final Method method = obj.getClass().getMethod("iterator", (Class[]) null);
- if (Iterator.class.isAssignableFrom(method.getReturnType())) {
- final Iterator<?> it = (Iterator<?>) method.invoke(obj, (Object[]) null);
- if (it != null) {
- return it;
- }
- }
- } catch (final RuntimeException | ReflectiveOperationException ignore) { // NOPMD
- // ignore
- }
- return singletonIterator(obj);
- }
-
- // Utility methods
-
- /**
- * Applies the closure to each element of the provided iterator.
- *
- * @param <E> the element type
- * @param iterator the iterator to use, may be null
- * @param closure the closure to apply to each element, may not be null
- * @throws NullPointerException if closure is null
- * @since 4.1
- */
- public static <E> void forEach(final Iterator<E> iterator, final Closure<? super E> closure) {
- Objects.requireNonNull(closure, "closure");
-
- if (iterator != null) {
- while (iterator.hasNext()) {
- final E element = iterator.next();
- closure.execute(element);
- }
- }
- }
-
- /**
- * Executes the given closure on each but the last element in the iterator.
- * <p>
- * If the input iterator is null no change is made.
- *
- * @param <E> the type of object the {@link Iterator} contains
- * @param iterator the iterator to get the input from, may be null
- * @param closure the closure to perform, may not be null
- * @return the last element in the iterator, or null if iterator is null or empty
- * @throws NullPointerException if closure is null
- * @since 4.1
- */
- public static <E> E forEachButLast(final Iterator<E> iterator, final Closure<? super E> closure) {
- Objects.requireNonNull(closure, "closure");
-
- if (iterator != null) {
- while (iterator.hasNext()) {
- final E element = iterator.next();
- if (!iterator.hasNext()) {
- return element;
- }
- closure.execute(element);
- }
- }
- return null;
- }
-
- /**
- * Finds the first element in the given iterator which matches the given predicate.
- * <p>
- * A {@code null} or empty iterator returns null.
- *
- * @param <E> the element type
- * @param iterator the iterator to search, may be null
- * @param predicate the predicate to use, must not be null
- * @return the first element of the iterator which matches the predicate or null if none could be found
- * @throws NullPointerException if predicate is null
- * @since 4.1
- */
- public static <E> E find(final Iterator<E> iterator, final Predicate<? super E> predicate) {
- Objects.requireNonNull(predicate, "predicate");
-
- if (iterator != null) {
- while (iterator.hasNext()) {
- final E element = iterator.next();
- if (predicate.evaluate(element)) {
- return element;
+ return new ArrayIterator<>(obj);
+ }
+ try {
+ final Method method = obj.getClass().getMethod("iterator", (Class[]) null);
+ if (Iterator.class.isAssignableFrom(method.getReturnType())) {
+ final Iterator<?> it = (Iterator<?>) method.invoke(obj, (Object[]) null);
+ if (it != null) {
+ return it;
}
}
+ } catch (final RuntimeException | ReflectiveOperationException ignore) { // NOPMD
+ // ignore
}
- return null;
+ return singletonIterator(obj);
}
+ // Peeking
+
/**
* Returns the index of the first element in the specified iterator that
* matches the given predicate.
@@ -1220,20 +870,52 @@ public class IteratorUtils {
return CollectionUtils.INDEX_NOT_FOUND;
}
+ // Pushback
+
/**
- * Answers true if a predicate is true for any element of the iterator.
+ * Checks if the given iterator is empty.
* <p>
- * A {@code null} or empty iterator returns false.
+ * A {@code null} or empty iterator returns true.
*
- * @param <E> the type of object the {@link Iterator} contains
* @param iterator the {@link Iterator} to use, may be null
- * @param predicate the predicate to use, may not be null
- * @return true if any element of the collection matches the predicate, false otherwise
- * @throws NullPointerException if predicate is null
+ * @return true if the iterator is exhausted or null, false otherwise
* @since 4.1
*/
- public static <E> boolean matchesAny(final Iterator<E> iterator, final Predicate<? super E> predicate) {
- return indexOf(iterator, predicate) != -1;
+ public static boolean isEmpty(final Iterator<?> iterator) {
+ return iterator == null || !iterator.hasNext();
+ }
+
+ // Looping
+ /**
+ * Gets an iterator that loops continuously over the supplied collection.
+ * <p>
+ * The iterator will only stop looping if the remove method is called
+ * enough times to empty the collection, or if the collection is empty
+ * to start with.
+ *
+ * @param <E> the element type
+ * @param collection the collection to iterate over, not null
+ * @return a new looping iterator
+ * @throws NullPointerException if the collection is null
+ */
+ public static <E> ResettableIterator<E> loopingIterator(final Collection<? extends E> collection) {
+ return new LoopingIterator<>(Objects.requireNonNull(collection, "collection"));
+ }
+
+ /**
+ * Gets an iterator that loops continuously over the supplied list.
+ * <p>
+ * The iterator will only stop looping if the remove method is called
+ * enough times to empty the list, or if the list is empty to start with.
+ *
+ * @param <E> the element type
+ * @param list the list to iterate over, not null
+ * @return a new looping iterator
+ * @throws NullPointerException if the list is null
+ * @since 3.2
+ */
+ public static <E> ResettableListIterator<E> loopingListIterator(final List<E> list) {
+ return new LoopingListIterator<>(Objects.requireNonNull(list, "list"));
}
/**
@@ -1264,98 +946,301 @@ public class IteratorUtils {
}
/**
- * Checks if the given iterator is empty.
+ * Answers true if a predicate is true for any element of the iterator.
+ * <p>
+ * A {@code null} or empty iterator returns false.
+ *
+ * @param <E> the type of object the {@link Iterator} contains
+ * @param iterator the {@link Iterator} to use, may be null
+ * @param predicate the predicate to use, may not be null
+ * @return true if any element of the collection matches the predicate, false otherwise
+ * @throws NullPointerException if predicate is null
+ * @since 4.1
+ */
+ public static <E> boolean matchesAny(final Iterator<E> iterator, final Predicate<? super E> predicate) {
+ return indexOf(iterator, predicate) != -1;
+ }
+
+ /**
+ * Gets an {@link Iterator} that wraps the specified node's childNodes.
+ * The returned {@link Iterator} can be used for a single iteration.
+ * <p>
+ * Convenience method, allows easy iteration over NodeLists:
+ * <pre>
+ * Iterator<Node> iterator = IteratorUtils.nodeListIterator(node);
+ * for (Node childNode : IteratorUtils.asIterable(iterator)) {
+ * ...
+ * }
+ * </pre>
+ *
+ * @param node the node to use, may not be null
+ * @return a new, single use {@link Iterator}
+ * @throws NullPointerException if node is null
+ * @since 4.0
+ */
+ public static NodeListIterator nodeListIterator(final Node node) {
+ return new NodeListIterator(Objects.requireNonNull(node, "node"));
+ }
+
+ // org.w3c.dom.NodeList iterators
+ /**
+ * Gets an {@link Iterator} that wraps the specified {@link NodeList}.
+ * The returned {@link Iterator} can be used for a single iteration.
+ *
+ * @param nodeList the node list to use, may not be null
+ * @return a new, single use {@link Iterator}
+ * @throws NullPointerException if nodeList is null
+ * @since 4.0
+ */
+ public static NodeListIterator nodeListIterator(final NodeList nodeList) {
+ return new NodeListIterator(Objects.requireNonNull(nodeList, "nodeList"));
+ }
+
+ // Object Graph
+ /**
+ * Gets an iterator that operates over an object graph.
+ * <p>
+ * This iterator can extract multiple objects from a complex tree-like object graph.
+ * The iteration starts from a single root object.
+ * It uses a {@code Transformer} to extract the iterators and elements.
+ * Its main benefit is that no intermediate {@code List} is created.
+ * <p>
+ * For example, consider an object graph:
+ * <pre>
+ * |- Branch -- Leaf
+ * | \- Leaf
+ * |- Tree | /- Leaf
+ * | |- Branch -- Leaf
+ * Forest | \- Leaf
+ * | |- Branch -- Leaf
+ * | | \- Leaf
+ * |- Tree | /- Leaf
+ * |- Branch -- Leaf
+ * |- Branch -- Leaf</pre>
+ * The following {@code Transformer}, used in this class, will extract all
+ * the Leaf objects without creating a combined intermediate list:
+ * <pre>
+ * public Object transform(Object input) {
+ * if (input instanceof Forest) {
+ * return ((Forest) input).treeIterator();
+ * }
+ * if (input instanceof Tree) {
+ * return ((Tree) input).branchIterator();
+ * }
+ * if (input instanceof Branch) {
+ * return ((Branch) input).leafIterator();
+ * }
+ * if (input instanceof Leaf) {
+ * return input;
+ * }
+ * throw new ClassCastException();
+ * }</pre>
+ * <p>
+ * Internally, iteration starts from the root object. When next is called,
+ * the transformer is called to examine the object. The transformer will return
+ * either an iterator or an object. If the object is an Iterator, the next element
+ * from that iterator is obtained and the process repeats. If the element is an object
+ * it is returned.
+ * <p>
+ * Under many circumstances, linking Iterators together in this manner is
+ * more efficient (and convenient) than using nested for loops to extract a list.
+ *
+ * @param <E> the element type
+ * @param root the root object to start iterating from, null results in an empty iterator
+ * @param transformer the transformer to use, see above, null uses no effect transformer
+ * @return a new object graph iterator
+ * @since 3.1
+ */
+ public static <E> Iterator<E> objectGraphIterator(final E root,
+ final Transformer<? super E, ? extends E> transformer) {
+ return new ObjectGraphIterator<>(root, transformer);
+ }
+
+ /**
+ * Gets an iterator that supports one-element lookahead.
+ *
+ * @param <E> the element type
+ * @param iterator the iterator to decorate, not null
+ * @return a peeking iterator
+ * @throws NullPointerException if the iterator is null
+ * @since 4.0
+ */
+ public static <E> Iterator<E> peekingIterator(final Iterator<? extends E> iterator) {
+ return PeekingIterator.peekingIterator(iterator);
+ }
+
+ /**
+ * Gets an iterator that supports pushback of elements.
+ *
+ * @param <E> the element type
+ * @param iterator the iterator to decorate, not null
+ * @return a pushback iterator
+ * @throws NullPointerException if the iterator is null
+ * @since 4.0
+ */
+ public static <E> Iterator<E> pushbackIterator(final Iterator<? extends E> iterator) {
+ return PushbackIterator.pushbackIterator(iterator);
+ }
+
+ // Singleton
+ /**
+ * Gets a singleton iterator.
+ * <p>
+ * This iterator is a valid iterator object that will iterate over
+ * the specified object.
+ *
+ * @param <E> the element type
+ * @param object the single object over which to iterate
+ * @return a singleton iterator over the object
+ */
+ public static <E> ResettableIterator<E> singletonIterator(final E object) {
+ return new SingletonIterator<>(object);
+ }
+
+ /**
+ * Gets a singleton list iterator.
+ * <p>
+ * This iterator is a valid list iterator object that will iterate over
+ * the specified object.
+ *
+ * @param <E> the element type
+ * @param object the single object over which to iterate
+ * @return a singleton list iterator over the object
+ */
+ public static <E> ListIterator<E> singletonListIterator(final E object) {
+ return new SingletonListIterator<>(object);
+ }
+
+ /**
+ * Returns the number of elements contained in the given iterator.
+ * <p>
+ * A {@code null} or empty iterator returns {@code 0}.
+ *
+ * @param iterator the iterator to check, may be null
+ * @return the number of elements contained in the iterator
+ * @since 4.1
+ */
+ public static int size(final Iterator<?> iterator) {
+ int size = 0;
+ if (iterator != null) {
+ while (iterator.hasNext()) {
+ iterator.next();
+ size++;
+ }
+ }
+ return size;
+ }
+
+ // Skipping
+ /**
+ * Decorates the specified iterator to skip the first N elements.
+ *
+ * @param <E> the element type
+ * @param iterator the iterator to decorate
+ * @param offset the first number of elements to skip
+ * @return a new skipping iterator
+ * @throws NullPointerException if the iterator is null
+ * @throws IllegalArgumentException if offset is negative
+ * @since 4.1
+ */
+ public static <E> SkippingIterator<E> skippingIterator(final Iterator<E> iterator, final long offset) {
+ return new SkippingIterator<>(iterator, offset);
+ }
+
+ /**
+ * Gets an array based on an iterator.
* <p>
- * A {@code null} or empty iterator returns true.
+ * As the wrapped Iterator is traversed, an ArrayList of its values is
+ * created. At the end, this is converted to an array.
*
- * @param iterator the {@link Iterator} to use, may be null
- * @return true if the iterator is exhausted or null, false otherwise
- * @since 4.1
+ * @param iterator the iterator to use, not null
+ * @return an array of the iterator contents
+ * @throws NullPointerException if iterator parameter is null
*/
- public static boolean isEmpty(final Iterator<?> iterator) {
- return iterator == null || !iterator.hasNext();
+ public static Object[] toArray(final Iterator<?> iterator) {
+ Objects.requireNonNull(iterator, "iterator");
+ final List<?> list = toList(iterator, 100);
+ return list.toArray();
}
/**
- * Checks if the object is contained in the given iterator.
+ * Gets an array based on an iterator.
* <p>
- * A {@code null} or empty iterator returns false.
+ * As the wrapped Iterator is traversed, an ArrayList of its values is
+ * created. At the end, this is converted to an array.
*
- * @param <E> the type of object the {@link Iterator} contains
- * @param iterator the iterator to check, may be null
- * @param object the object to check
- * @return true if the object is contained in the iterator, false otherwise
- * @since 4.1
+ * @param <E> the element type
+ * @param iterator the iterator to use, not null
+ * @param arrayClass the class of array to create
+ * @return an array of the iterator contents
+ * @throws NullPointerException if iterator parameter or arrayClass is null
+ * @throws ArrayStoreException if the arrayClass is invalid
*/
- public static <E> boolean contains(final Iterator<E> iterator, final Object object) {
- return matchesAny(iterator, EqualPredicate.equalPredicate(object));
+ public static <E> E[] toArray(final Iterator<? extends E> iterator, final Class<E> arrayClass) {
+ Objects.requireNonNull(iterator, "iterator");
+ Objects.requireNonNull(arrayClass, "arrayClass");
+ final List<E> list = toList(iterator, 100);
+ @SuppressWarnings("unchecked")
+ final E[] array = (E[]) Array.newInstance(arrayClass, list.size());
+ return list.toArray(array);
}
+ // Utility methods
+
/**
- * Returns the {@code index}-th value in {@link Iterator}, throwing
- * {@code IndexOutOfBoundsException} if there is no such element.
+ * Gets a list based on an iterator.
* <p>
- * The Iterator is advanced to {@code index} (or to the end, if
- * {@code index} exceeds the number of entries) as a side effect of this method.
+ * As the wrapped Iterator is traversed, an ArrayList of its values is
+ * created. At the end, the list is returned.
*
- * @param <E> the type of object in the {@link Iterator}
- * @param iterator the iterator to get a value from
- * @param index the index to get
- * @return the object at the specified index
- * @throws IndexOutOfBoundsException if the index is invalid
- * @since 4.1
+ * @param <E> the element type
+ * @param iterator the iterator to use, not null
+ * @return a list of the iterator contents
+ * @throws NullPointerException if iterator parameter is null
*/
- public static <E> E get(final Iterator<E> iterator, final int index) {
- int i = index;
- CollectionUtils.checkIndexBounds(i);
- while (iterator.hasNext()) {
- i--;
- if (i == -1) {
- return iterator.next();
- }
- iterator.next();
- }
- throw new IndexOutOfBoundsException("Entry does not exist: " + i);
+ public static <E> List<E> toList(final Iterator<? extends E> iterator) {
+ return toList(iterator, 10);
}
/**
- * Shortcut for {@code get(iterator, 0)}.
- * <p>
- * Returns the {@code first} value in {@link Iterator}, throwing
- * {@code IndexOutOfBoundsException} if there is no such element.
- * </p>
+ * Gets a list based on an iterator.
* <p>
- * The Iterator is advanced to {@code 0} (or to the end, if
- * {@code 0} exceeds the number of entries) as a side effect of this method.
- * </p>
- * @param <E> the type of object in the {@link Iterator}
- * @param iterator the iterator to get a value from
- * @return the first object
- * @throws IndexOutOfBoundsException if the request is invalid
- * @since 4.2
+ * As the wrapped Iterator is traversed, an ArrayList of its values is
+ * created. At the end, the list is returned.
+ *
+ * @param <E> the element type
+ * @param iterator the iterator to use, not null
+ * @param estimatedSize the initial size of the ArrayList
+ * @return a list of the iterator contents
+ * @throws NullPointerException if iterator parameter is null
+ * @throws IllegalArgumentException if the size is less than 1
*/
- public static <E> E first(final Iterator<E> iterator) {
- return get(iterator, 0);
+ public static <E> List<E> toList(final Iterator<? extends E> iterator, final int estimatedSize) {
+ Objects.requireNonNull(iterator, "iterator");
+ if (estimatedSize < 1) {
+ throw new IllegalArgumentException("Estimated size must be greater than 0");
+ }
+ final List<E> list = new ArrayList<>(estimatedSize);
+ while (iterator.hasNext()) {
+ list.add(iterator.next());
+ }
+ return list;
}
/**
- * Returns the number of elements contained in the given iterator.
+ * Gets a list iterator based on a simple iterator.
* <p>
- * A {@code null} or empty iterator returns {@code 0}.
+ * As the wrapped Iterator is traversed, a LinkedList of its values is
+ * cached, permitting all required operations of ListIterator.
*
- * @param iterator the iterator to check, may be null
- * @return the number of elements contained in the iterator
- * @since 4.1
+ * @param <E> the element type
+ * @param iterator the iterator to use, may not be null
+ * @return a new iterator
+ * @throws NullPointerException if iterator parameter is null
*/
- public static int size(final Iterator<?> iterator) {
- int size = 0;
- if (iterator != null) {
- while (iterator.hasNext()) {
- iterator.next();
- size++;
- }
- }
- return size;
+ public static <E> ListIterator<E> toListIterator(final Iterator<? extends E> iterator) {
+ Objects.requireNonNull(iterator, "iterator");
+ return new ListIteratorWrapper<>(iterator);
}
/**
@@ -1440,4 +1325,119 @@ public class IteratorUtils {
return stringBuilder.toString();
}
+ // Transformed
+ /**
+ * Gets an iterator that transforms the elements of another iterator.
+ * <p>
+ * The transformation occurs during the next() method and the underlying
+ * iterator is unaffected by the transformation.
+ *
+ * @param <I> the input type
+ * @param <O> the output type
+ * @param iterator the iterator to use, not null
+ * @param transformer the transform to use, not null
+ * @return a new transforming iterator
+ * @throws NullPointerException if either parameter is null
+ */
+ public static <I, O> Iterator<O> transformedIterator(final Iterator<? extends I> iterator,
+ final Transformer<? super I, ? extends O> transformer) {
+
+ Objects.requireNonNull(iterator, "iterator");
+ Objects.requireNonNull(transformer, "transformer");
+ return new TransformIterator<>(iterator, transformer);
+ }
+
+ // Unmodifiable
+ /**
+ * Gets an immutable version of an {@link Iterator}. The returned object
+ * will always throw an {@link UnsupportedOperationException} for
+ * the {@link Iterator#remove} method.
+ *
+ * @param <E> the element type
+ * @param iterator the iterator to make immutable
+ * @return an immutable version of the iterator
+ */
+ public static <E> Iterator<E> unmodifiableIterator(final Iterator<E> iterator) {
+ return UnmodifiableIterator.unmodifiableIterator(iterator);
+ }
+
+ /**
+ * Gets an immutable version of a {@link ListIterator}. The returned object
+ * will always throw an {@link UnsupportedOperationException} for
+ * the {@link Iterator#remove}, {@link ListIterator#add} and
+ * {@link ListIterator#set} methods.
+ *
+ * @param <E> the element type
+ * @param listIterator the iterator to make immutable
+ * @return an immutable version of the iterator
+ */
+ public static <E> ListIterator<E> unmodifiableListIterator(final ListIterator<E> listIterator) {
+ return UnmodifiableListIterator.unmodifiableListIterator(listIterator);
+ }
+
+ /**
+ * Gets an immutable version of a {@link MapIterator}. The returned object
+ * will always throw an {@link UnsupportedOperationException} for
+ * the {@link Iterator#remove}, {@link MapIterator#setValue(Object)} methods.
+ *
+ * @param <K> the key type
+ * @param <V> the value type
+ * @param mapIterator the iterator to make immutable
+ * @return an immutable version of the iterator
+ */
+ public static <K, V> MapIterator<K, V> unmodifiableMapIterator(final MapIterator<K, V> mapIterator) {
+ return UnmodifiableMapIterator.unmodifiableMapIterator(mapIterator);
+ }
+
+ /**
+ * Returns an iterator that interleaves elements from the decorated iterators.
+ *
+ * @param <E> the element type
+ * @param iterators the array of iterators to interleave
+ * @return an iterator, interleaving the decorated iterators
+ * @throws NullPointerException if any iterator is null
+ * @since 4.1
+ */
+ public static <E> ZippingIterator<E> zippingIterator(final Iterator<? extends E>... iterators) {
+ return new ZippingIterator<>(iterators);
+ }
+
+ // Zipping
+ /**
+ * Returns an iterator that interleaves elements from the decorated iterators.
+ *
+ * @param <E> the element type
+ * @param a the first iterator to interleave
+ * @param b the second iterator to interleave
+ * @return an iterator, interleaving the decorated iterators
+ * @throws NullPointerException if any iterator is null
+ * @since 4.1
+ */
+ public static <E> ZippingIterator<E> zippingIterator(final Iterator<? extends E> a,
+ final Iterator<? extends E> b) {
+ return new ZippingIterator<>(a, b);
+ }
+
+ /**
+ * Returns an iterator that interleaves elements from the decorated iterators.
+ *
+ * @param <E> the element type
+ * @param a the first iterator to interleave
+ * @param b the second iterator to interleave
+ * @param c the third iterator to interleave
+ * @return an iterator, interleaving the decorated iterators
+ * @throws NullPointerException if any iterator is null
+ * @since 4.1
+ */
+ public static <E> ZippingIterator<E> zippingIterator(final Iterator<? extends E> a,
+ final Iterator<? extends E> b,
+ final Iterator<? extends E> c) {
+ return new ZippingIterator<>(a, b, c);
+ }
+
+ /**
+ * Don't allow instances.
+ */
+ private IteratorUtils() {}
+
}
diff --git a/src/main/java/org/apache/commons/collections4/MapIterator.java b/src/main/java/org/apache/commons/collections4/MapIterator.java
index 0de434120..54cd88e76 100644
--- a/src/main/java/org/apache/commons/collections4/MapIterator.java
+++ b/src/main/java/org/apache/commons/collections4/MapIterator.java
@@ -49,23 +49,6 @@ import java.util.Iterator;
*/
public interface MapIterator<K, V> extends Iterator<K> {
- /**
- * Checks to see if there are more entries still to be iterated.
- *
- * @return {@code true} if the iterator has more elements
- */
- @Override
- boolean hasNext();
-
- /**
- * Gets the next <em>key</em> from the {@code Map}.
- *
- * @return the next key in the iteration
- * @throws java.util.NoSuchElementException if the iteration is finished
- */
- @Override
- K next();
-
/**
* Gets the current key, which is the key returned by the last call
* to {@code next()}.
@@ -84,6 +67,23 @@ public interface MapIterator<K, V> extends Iterator<K> {
*/
V getValue();
+ /**
+ * Checks to see if there are more entries still to be iterated.
+ *
+ * @return {@code true} if the iterator has more elements
+ */
+ @Override
+ boolean hasNext();
+
+ /**
+ * Gets the next <em>key</em> from the {@code Map}.
+ *
+ * @return the next key in the iteration
+ * @throws java.util.NoSuchElementException if the iteration is finished
+ */
+ @Override
+ K next();
+
/**
* Removes the last returned key from the underlying {@code Map} (optional operation).
* <p>
diff --git a/src/main/java/org/apache/commons/collections4/MultiMap.java b/src/main/java/org/apache/commons/collections4/MultiMap.java
index bee6f8419..1e10fda86 100644
--- a/src/main/java/org/apache/commons/collections4/MultiMap.java
+++ b/src/main/java/org/apache/commons/collections4/MultiMap.java
@@ -53,35 +53,18 @@ import java.util.Collection;
public interface MultiMap<K, V> extends IterableMap<K, Object> {
/**
- * Removes a specific value from map.
- * <p>
- * The item is removed from the collection mapped to the specified key.
- * Other values attached to that key are unaffected.
- * <p>
- * If the last value for a key is removed, implementations typically
- * return {@code null} from a subsequent {@code get(Object)}, however
- * they may choose to return an empty collection.
- *
- * @param key the key to remove from
- * @param item the item to remove
- * @return {@code true} if the mapping was removed, {@code false} otherwise
- * @throws UnsupportedOperationException if the map is unmodifiable
- * @throws ClassCastException if the key or value is of an invalid type
- * @throws NullPointerException if the key or value is null and null is invalid
- * @since 4.0 (signature in previous releases: V remove(K, V))
- */
- boolean removeMapping(K key, V item);
-
- /**
- * Gets the number of keys in this map.
+ * Checks whether the map contains the value specified.
* <p>
- * Implementations typically return only the count of keys in the map
+ * Implementations typically check all collections against all keys for the value.
* This cannot be mandated due to backwards compatibility of this interface.
*
- * @return the number of key-collection mappings in this map
+ * @param value the value to search for
+ * @return true if the map contains the value
+ * @throws ClassCastException if the value is of an invalid type
+ * @throws NullPointerException if the value is null and null value are invalid
*/
@Override
- int size();
+ boolean containsValue(Object value);
/**
* Gets the collection of values associated with the specified key.
@@ -105,20 +88,6 @@ public interface MultiMap<K, V> extends IterableMap<K, Object> {
@Override
Object get(Object key); // Cannot use get(K key) as that does not properly implement Map#get
- /**
- * Checks whether the map contains the value specified.
- * <p>
- * Implementations typically check all collections against all keys for the value.
- * This cannot be mandated due to backwards compatibility of this interface.
- *
- * @param value the value to search for
- * @return true if the map contains the value
- * @throws ClassCastException if the value is of an invalid type
- * @throws NullPointerException if the value is null and null value are invalid
- */
- @Override
- boolean containsValue(Object value);
-
/**
* Adds the value to the collection associated with the specified key.
* <p>
@@ -154,6 +123,37 @@ public interface MultiMap<K, V> extends IterableMap<K, Object> {
@Override
Object remove(Object key); // Cannot use remove(K key) as that does not properly implement Map#remove
+ /**
+ * Removes a specific value from map.
+ * <p>
+ * The item is removed from the collection mapped to the specified key.
+ * Other values attached to that key are unaffected.
+ * <p>
+ * If the last value for a key is removed, implementations typically
+ * return {@code null} from a subsequent {@code get(Object)}, however
+ * they may choose to return an empty collection.
+ *
+ * @param key the key to remove from
+ * @param item the item to remove
+ * @return {@code true} if the mapping was removed, {@code false} otherwise
+ * @throws UnsupportedOperationException if the map is unmodifiable
+ * @throws ClassCastException if the key or value is of an invalid type
+ * @throws NullPointerException if the key or value is null and null is invalid
+ * @since 4.0 (signature in previous releases: V remove(K, V))
+ */
+ boolean removeMapping(K key, V item);
+
+ /**
+ * Gets the number of keys in this map.
+ * <p>
+ * Implementations typically return only the count of keys in the map
+ * This cannot be mandated due to backwards compatibility of this interface.
+ *
+ * @return the number of key-collection mappings in this map
+ */
+ @Override
+ int size();
+
/**
* Gets a collection containing all the values in the map.
* <p>
diff --git a/src/main/java/org/apache/commons/collections4/MultiMapUtils.java b/src/main/java/org/apache/commons/collections4/MultiMapUtils.java
index fe3771d4a..d17dd53de 100644
--- a/src/main/java/org/apache/commons/collections4/MultiMapUtils.java
+++ b/src/main/java/org/apache/commons/collections4/MultiMapUtils.java
@@ -43,11 +43,6 @@ import org.apache.commons.collections4.multimap.UnmodifiableMultiValuedMap;
*/
public class MultiMapUtils {
- /**
- * Don't allow instances.
- */
- private MultiMapUtils() {}
-
/**
* An empty {@link UnmodifiableMultiValuedMap}.
*/
@@ -55,20 +50,6 @@ public class MultiMapUtils {
public static final MultiValuedMap EMPTY_MULTI_VALUED_MAP =
UnmodifiableMultiValuedMap.unmodifiableMultiValuedMap(new ArrayListValuedHashMap(0, 0));
- /**
- * Returns immutable EMPTY_MULTI_VALUED_MAP with generic type safety.
- *
- * @param <K> the type of key in the map
- * @param <V> the type of value in the map
- * @return immutable and empty {@code MultiValuedMap}
- */
- @SuppressWarnings("unchecked")
- public static <K, V> MultiValuedMap<K, V> emptyMultiValuedMap() {
- return EMPTY_MULTI_VALUED_MAP;
- }
-
- // Null safe methods
-
/**
* Returns an immutable empty {@code MultiValuedMap} if the argument is
* {@code null}, or the argument itself otherwise.
@@ -84,17 +65,19 @@ public class MultiMapUtils {
}
/**
- * Null-safe check if the specified {@code MultiValuedMap} is empty.
- * <p>
- * If the provided map is null, returns true.
+ * Returns immutable EMPTY_MULTI_VALUED_MAP with generic type safety.
*
- * @param map the map to check, may be null
- * @return true if the map is empty or null
+ * @param <K> the type of key in the map
+ * @param <V> the type of value in the map
+ * @return immutable and empty {@code MultiValuedMap}
*/
- public static boolean isEmpty(final MultiValuedMap<?, ?> map) {
- return map == null || map.isEmpty();
+ @SuppressWarnings("unchecked")
+ public static <K, V> MultiValuedMap<K, V> emptyMultiValuedMap() {
+ return EMPTY_MULTI_VALUED_MAP;
}
+ // Null safe methods
+
/**
* Gets a Collection from {@code MultiValuedMap} in a null-safe manner.
*
@@ -111,8 +94,25 @@ public class MultiMapUtils {
return null;
}
- // TODO: review the getValuesAsXXX methods - depending on the actual MultiValuedMap type, changes
- // to the returned collection might update the backing map. This should be clarified and/or prevented.
+ /**
+ * Gets a Bag from {@code MultiValuedMap} in a null-safe manner.
+ *
+ * @param <K> the key type
+ * @param <V> the value type
+ * @param map the {@link MultiValuedMap} to use
+ * @param key the key to look up
+ * @return the Collection in the {@link MultiValuedMap} as Bag, or null if input map is null
+ */
+ public static <K, V> Bag<V> getValuesAsBag(final MultiValuedMap<K, V> map, final K key) {
+ if (map != null) {
+ final Collection<V> col = map.get(key);
+ if (col instanceof Bag) {
+ return (Bag<V>) col;
+ }
+ return new HashBag<>(col);
+ }
+ return null;
+ }
/**
* Gets a List from {@code MultiValuedMap} in a null-safe manner.
@@ -134,6 +134,9 @@ public class MultiMapUtils {
return null;
}
+ // TODO: review the getValuesAsXXX methods - depending on the actual MultiValuedMap type, changes
+ // to the returned collection might update the backing map. This should be clarified and/or prevented.
+
/**
* Gets a Set from {@code MultiValuedMap} in a null-safe manner.
*
@@ -155,23 +158,15 @@ public class MultiMapUtils {
}
/**
- * Gets a Bag from {@code MultiValuedMap} in a null-safe manner.
+ * Null-safe check if the specified {@code MultiValuedMap} is empty.
+ * <p>
+ * If the provided map is null, returns true.
*
- * @param <K> the key type
- * @param <V> the value type
- * @param map the {@link MultiValuedMap} to use
- * @param key the key to look up
- * @return the Collection in the {@link MultiValuedMap} as Bag, or null if input map is null
+ * @param map the map to check, may be null
+ * @return true if the map is empty or null
*/
- public static <K, V> Bag<V> getValuesAsBag(final MultiValuedMap<K, V> map, final K key) {
- if (map != null) {
- final Collection<V> col = map.get(key);
- if (col instanceof Bag) {
- return (Bag<V>) col;
- }
- return new HashBag<>(col);
- }
- return null;
+ public static boolean isEmpty(final MultiValuedMap<?, ?> map) {
+ return map == null || map.isEmpty();
}
/**
@@ -198,21 +193,6 @@ public class MultiMapUtils {
return new HashSetValuedHashMap<>();
}
- /**
- * Returns an {@code UnmodifiableMultiValuedMap} backed by the given
- * map.
- *
- * @param <K> the key type
- * @param <V> the value type
- * @param map the {@link MultiValuedMap} to decorate, must not be null
- * @return an unmodifiable {@link MultiValuedMap} backed by the provided map
- * @throws NullPointerException if map is null
- */
- public static <K, V> MultiValuedMap<K, V> unmodifiableMultiValuedMap(
- final MultiValuedMap<? extends K, ? extends V> map) {
- return UnmodifiableMultiValuedMap.<K, V>unmodifiableMultiValuedMap(map);
- }
-
/**
* Returns a {@code TransformedMultiValuedMap} backed by the given map.
* <p>
@@ -242,4 +222,24 @@ public class MultiMapUtils {
return TransformedMultiValuedMap.transformingMap(map, keyTransformer, valueTransformer);
}
+ /**
+ * Returns an {@code UnmodifiableMultiValuedMap} backed by the given
+ * map.
+ *
+ * @param <K> the key type
+ * @param <V> the value type
+ * @param map the {@link MultiValuedMap} to decorate, must not be null
+ * @return an unmodifiable {@link MultiValuedMap} backed by the provided map
+ * @throws NullPointerException if map is null
+ */
+ public static <K, V> MultiValuedMap<K, V> unmodifiableMultiValuedMap(
+ final MultiValuedMap<? extends K, ? extends V> map) {
+ return UnmodifiableMultiValuedMap.<K, V>unmodifiableMultiValuedMap(map);
+ }
+
+ /**
+ * Don't allow instances.
+ */
+ private MultiMapUtils() {}
+
}
diff --git a/src/main/java/org/apache/commons/collections4/MultiSet.java b/src/main/java/org/apache/commons/collections4/MultiSet.java
index 441b6a93c..5096ad586 100644
--- a/src/main/java/org/apache/commons/collections4/MultiSet.java
+++ b/src/main/java/org/apache/commons/collections4/MultiSet.java
@@ -35,29 +35,62 @@ import java.util.Set;
public interface MultiSet<E> extends Collection<E> {
/**
- * Returns the number of occurrences of the given object currently
- * in the MultiSet. If the object does not exist in the multiset,
- * return 0.
- *
- * @param object the object to search for
- * @return the number of occurrences of the object, zero if not found
- */
- int getCount(Object object);
-
- /**
- * Sets the number of occurrences of the specified object in the MultiSet
- * to the given count.
+ * An unmodifiable entry for an element and its occurrence as contained in a MultiSet.
* <p>
- * If the provided count is zero, the object will be removed from the
- * {@link #uniqueSet()}.
+ * The {@link MultiSet#entrySet()} method returns a view of the multiset whose elements
+ * implement this interface.
*
- * @param object the object to update
- * @param count the number of occurrences of the object
- * @return the number of occurrences of the object before this operation, zero
- * if the object was not contained in the multiset
- * @throws IllegalArgumentException if count is negative
+ * @param <E> the element type
*/
- int setCount(E object, int count);
+ interface Entry<E> {
+
+ /**
+ * Compares the specified object with this entry for equality.
+ * Returns true if the given object is also a multiset entry
+ * and the two entries represent the same element with the same
+ * number of occurrences.
+ * <p>
+ * More formally, two entries {@code e1} and {@code e2} represent
+ * the same mapping if
+ * <pre>
+ * (e1.getElement()==null ? e2.getElement()==null
+ * : e1.getElement().equals(e2.getElement())) &&
+ * (e1.getCount()==e2.getCount())
+ * </pre>
+ *
+ * @param o object to be compared for equality with this multiset entry
+ * @return true if the specified object is equal to this multiset entry
+ */
+ @Override
+ boolean equals(Object o);
+
+ /**
+ * Returns the number of occurrences for the element of this entry.
+ *
+ * @return the number of occurrences of the element
+ */
+ int getCount();
+
+ /**
+ * Returns the element corresponding to this entry.
+ *
+ * @return the element corresponding to this entry
+ */
+ E getElement();
+
+ /**
+ * Returns the hash code value for this multiset entry.
+ * <p>
+ * The hash code of a multiset entry {@code e} is defined to be:
+ * <pre>
+ * (e==null ? 0 : e.hashCode()) ^ noOccurrences)
+ * </pre>
+ *
+ * @return the hash code value for this multiset entry
+ */
+ @Override
+ int hashCode();
+ }
/**
* Adds one copy of the specified object to the MultiSet.
@@ -90,55 +123,57 @@ public interface MultiSet<E> extends Collection<E> {
int add(E object, int occurrences);
/**
- * Removes one occurrence of the given object from the MultiSet.
- * <p>
- * If the number of occurrences after this operation is reduced
- * to zero, the object will be removed from the {@link #uniqueSet()}.
+ * Returns {@code true} if the MultiSet contains at least one
+ * occurrence for each element contained in the given collection.
*
- * @param object the object to remove
- * @return {@code true} if this call changed the collection
+ * @param coll the collection to check against
+ * @return {@code true} if the MultiSet contains all the collection
*/
@Override
- boolean remove(Object object);
+ boolean containsAll(Collection<?> coll);
/**
- * Removes a number of occurrences of the specified object from the MultiSet.
+ * Returns a {@link Set} of all entries contained in the MultiSet.
* <p>
- * If the number of occurrences to remove is greater than the actual number of
- * occurrences in the multiset, the object will be removed from the multiset.
+ * The returned set is backed by this multiset, so any change to either
+ * is immediately reflected in the other.
*
- * @param object the object to remove
- * @param occurrences the number of occurrences to remove, may be zero,
- * in which case no change is made to the multiset
- * @return the number of occurrences of the object in the multiset
- * before the operation; possibly zero
- * @throws IllegalArgumentException if occurrences is negative
+ * @return the Set of MultiSet entries
*/
- int remove(Object object, int occurrences);
+ Set<Entry<E>> entrySet();
/**
- * Returns a {@link Set} of unique elements in the MultiSet.
- * <p>
- * Uniqueness constraints are the same as those in {@link java.util.Set}.
+ * Compares this MultiSet to another object.
* <p>
- * The returned set is backed by this multiset, so any change to either
- * is immediately reflected in the other. Only removal operations are
- * supported, in which case all occurrences of the element are removed
- * from the backing multiset.
+ * This MultiSet equals another object if it is also a MultiSet
+ * that contains the same number of occurrences of the same elements.
*
- * @return the Set of unique MultiSet elements
+ * @param obj the object to compare to
+ * @return true if equal
*/
- Set<E> uniqueSet();
+ @Override
+ boolean equals(Object obj);
/**
- * Returns a {@link Set} of all entries contained in the MultiSet.
- * <p>
- * The returned set is backed by this multiset, so any change to either
- * is immediately reflected in the other.
+ * Returns the number of occurrences of the given object currently
+ * in the MultiSet. If the object does not exist in the multiset,
+ * return 0.
*
- * @return the Set of MultiSet entries
+ * @param object the object to search for
+ * @return the number of occurrences of the object, zero if not found
*/
- Set<Entry<E>> entrySet();
+ int getCount(Object object);
+
+ /**
+ * Gets a hash code for the MultiSet compatible with the definition of equals.
+ * The hash code is defined as the sum total of a hash code for each element.
+ * The per element hash code is defined as
+ * {@code (e==null ? 0 : e.hashCode()) ^ noOccurrences)}.
+ *
+ * @return the hash code of the MultiSet
+ */
+ @Override
+ int hashCode();
/**
* Returns an {@link Iterator} over the entire set of members,
@@ -151,22 +186,31 @@ public interface MultiSet<E> extends Collection<E> {
Iterator<E> iterator();
/**
- * Returns the total number of items in the MultiSet.
+ * Removes one occurrence of the given object from the MultiSet.
+ * <p>
+ * If the number of occurrences after this operation is reduced
+ * to zero, the object will be removed from the {@link #uniqueSet()}.
*
- * @return the total size of the multiset
+ * @param object the object to remove
+ * @return {@code true} if this call changed the collection
*/
@Override
- int size();
+ boolean remove(Object object);
/**
- * Returns {@code true} if the MultiSet contains at least one
- * occurrence for each element contained in the given collection.
+ * Removes a number of occurrences of the specified object from the MultiSet.
+ * <p>
+ * If the number of occurrences to remove is greater than the actual number of
+ * occurrences in the multiset, the object will be removed from the multiset.
*
- * @param coll the collection to check against
- * @return {@code true} if the MultiSet contains all the collection
+ * @param object the object to remove
+ * @param occurrences the number of occurrences to remove, may be zero,
+ * in which case no change is made to the multiset
+ * @return the number of occurrences of the object in the multiset
+ * before the operation; possibly zero
+ * @throws IllegalArgumentException if occurrences is negative
*/
- @Override
- boolean containsAll(Collection<?> coll);
+ int remove(Object object, int occurrences);
/**
* Remove all occurrences of all elements from this MultiSet represented
@@ -189,84 +233,40 @@ public interface MultiSet<E> extends Collection<E> {
boolean retainAll(Collection<?> coll);
/**
- * Compares this MultiSet to another object.
+ * Sets the number of occurrences of the specified object in the MultiSet
+ * to the given count.
* <p>
- * This MultiSet equals another object if it is also a MultiSet
- * that contains the same number of occurrences of the same elements.
+ * If the provided count is zero, the object will be removed from the
+ * {@link #uniqueSet()}.
*
- * @param obj the object to compare to
- * @return true if equal
+ * @param object the object to update
+ * @param count the number of occurrences of the object
+ * @return the number of occurrences of the object before this operation, zero
+ * if the object was not contained in the multiset
+ * @throws IllegalArgumentException if count is negative
*/
- @Override
- boolean equals(Object obj);
+ int setCount(E object, int count);
/**
- * Gets a hash code for the MultiSet compatible with the definition of equals.
- * The hash code is defined as the sum total of a hash code for each element.
- * The per element hash code is defined as
- * {@code (e==null ? 0 : e.hashCode()) ^ noOccurrences)}.
+ * Returns the total number of items in the MultiSet.
*
- * @return the hash code of the MultiSet
+ * @return the total size of the multiset
*/
@Override
- int hashCode();
+ int size();
/**
- * An unmodifiable entry for an element and its occurrence as contained in a MultiSet.
+ * Returns a {@link Set} of unique elements in the MultiSet.
* <p>
- * The {@link MultiSet#entrySet()} method returns a view of the multiset whose elements
- * implement this interface.
+ * Uniqueness constraints are the same as those in {@link java.util.Set}.
+ * <p>
+ * The returned set is backed by this multiset, so any change to either
+ * is immediately reflected in the other. Only removal operations are
+ * supported, in which case all occurrences of the element are removed
+ * from the backing multiset.
*
- * @param <E> the element type
+ * @return the Set of unique MultiSet elements
*/
- interface Entry<E> {
-
- /**
- * Returns the element corresponding to this entry.
- *
- * @return the element corresponding to this entry
- */
- E getElement();
-
- /**
- * Returns the number of occurrences for the element of this entry.
- *
- * @return the number of occurrences of the element
- */
- int getCount();
-
- /**
- * Compares the specified object with this entry for equality.
- * Returns true if the given object is also a multiset entry
- * and the two entries represent the same element with the same
- * number of occurrences.
- * <p>
- * More formally, two entries {@code e1} and {@code e2} represent
- * the same mapping if
- * <pre>
- * (e1.getElement()==null ? e2.getElement()==null
- * : e1.getElement().equals(e2.getElement())) &&
- * (e1.getCount()==e2.getCount())
- * </pre>
- *
- * @param o object to be compared for equality with this multiset entry
- * @return true if the specified object is equal to this multiset entry
- */
- @Override
- boolean equals(Object o);
-
- /**
- * Returns the hash code value for this multiset entry.
- * <p>
- * The hash code of a multiset entry {@code e} is defined to be:
- * <pre>
- * (e==null ? 0 : e.hashCode()) ^ noOccurrences)
- * </pre>
- *
- * @return the hash code value for this multiset entry
- */
- @Override
- int hashCode();
- }
+ Set<E> uniqueSet();
}
diff --git a/src/main/java/org/apache/commons/collections4/MultiSetUtils.java b/src/main/java/org/apache/commons/collections4/MultiSetUtils.java
index 3e879d30e..e472b72da 100644
--- a/src/main/java/org/apache/commons/collections4/MultiSetUtils.java
+++ b/src/main/java/org/apache/commons/collections4/MultiSetUtils.java
@@ -36,9 +36,35 @@ public class MultiSetUtils {
UnmodifiableMultiSet.unmodifiableMultiSet(new HashMultiSet<>());
/**
- * Don't allow instances.
+ * Gets an empty {@code MultiSet}.
+ *
+ * @param <E> the element type
+ * @return an empty MultiSet
*/
- private MultiSetUtils() {}
+ @SuppressWarnings("unchecked") // OK, empty multiset is compatible with any type
+ public static <E> MultiSet<E> emptyMultiSet() {
+ return EMPTY_MULTISET;
+ }
+
+ /**
+ * Returns a predicated (validating) multiset backed by the given multiset.
+ * <p>
+ * Only objects that pass the test in the given predicate can be added to
+ * the multiset. Trying to add an invalid object results in an
+ * IllegalArgumentException. It is important not to use the original multiset
+ * after invoking this method, as it is a backdoor for adding invalid
+ * objects.
+ *
+ * @param <E> the element type
+ * @param multiset the multiset to predicate, must not be null
+ * @param predicate the predicate for the multiset, must not be null
+ * @return a predicated multiset backed by the given multiset
+ * @throws NullPointerException if the MultiSet or Predicate is null
+ */
+ public static <E> MultiSet<E> predicatedMultiSet(final MultiSet<E> multiset,
+ final Predicate<? super E> predicate) {
+ return PredicatedMultiSet.predicatedMultiSet(multiset, predicate);
+ }
/**
* Returns a synchronized (thread-safe) multiset backed by the given multiset.
@@ -84,34 +110,8 @@ public class MultiSetUtils {
}
/**
- * Returns a predicated (validating) multiset backed by the given multiset.
- * <p>
- * Only objects that pass the test in the given predicate can be added to
- * the multiset. Trying to add an invalid object results in an
- * IllegalArgumentException. It is important not to use the original multiset
- * after invoking this method, as it is a backdoor for adding invalid
- * objects.
- *
- * @param <E> the element type
- * @param multiset the multiset to predicate, must not be null
- * @param predicate the predicate for the multiset, must not be null
- * @return a predicated multiset backed by the given multiset
- * @throws NullPointerException if the MultiSet or Predicate is null
- */
- public static <E> MultiSet<E> predicatedMultiSet(final MultiSet<E> multiset,
- final Predicate<? super E> predicate) {
- return PredicatedMultiSet.predicatedMultiSet(multiset, predicate);
- }
-
- /**
- * Gets an empty {@code MultiSet}.
- *
- * @param <E> the element type
- * @return an empty MultiSet
+ * Don't allow instances.
*/
- @SuppressWarnings("unchecked") // OK, empty multiset is compatible with any type
- public static <E> MultiSet<E> emptyMultiSet() {
- return EMPTY_MULTISET;
- }
+ private MultiSetUtils() {}
}
diff --git a/src/main/java/org/apache/commons/collections4/MultiValuedMap.java b/src/main/java/org/apache/commons/collections4/MultiValuedMap.java
index 2c3975809..1e0c1cf60 100644
--- a/src/main/java/org/apache/commons/collections4/MultiValuedMap.java
+++ b/src/main/java/org/apache/commons/collections4/MultiValuedMap.java
@@ -52,22 +52,33 @@ public interface MultiValuedMap<K, V> {
// Query operations
/**
- * Gets the total size of the map.
+ * Returns a view of this multivalued map as a {@code Map} from each distinct
+ * key to the non-empty collection of that key's associated values.
* <p>
- * Implementations would return the total size of the map which is the count
- * of the values from all keys.
+ * Note that {@code this.asMap().get(k)} is equivalent to {@code this.get(k)}
+ * only when {@code k} is a key contained in the multivalued map; otherwise it
+ * returns {@code null} as opposed to an empty collection.
+ * </p>
+ * <p>
+ * Changes to the returned map or the collections that serve as its values
+ * will update the underlying multivalued map, and vice versa. The map does
+ * not support {@code put} or {@code putAll}, nor do its entries support
+ * {@link java.util.Map.Entry#setValue(Object) setValue}.
* </p>
*
- * @return the total size of the map
+ * @return a map view of the mappings in this multivalued map
*/
- int size();
+ Map<K, Collection<V>> asMap();
/**
- * Returns {@code true} if this map contains no key-value mappings.
+ * Removes all of the mappings from this map (optional operation).
+ * <p>
+ * The map will be empty after this call returns.
+ * </p>
*
- * @return {@code true} if this map contains no key-value mappings
+ * @throws UnsupportedOperationException if the map is unmodifiable
*/
- boolean isEmpty();
+ void clear();
/**
* Returns {@code true} if this map contains a mapping for the specified
@@ -82,6 +93,15 @@ public interface MultiValuedMap<K, V> {
*/
boolean containsKey(Object key);
+ /**
+ * Checks whether the map contains a mapping for the specified key and value.
+ *
+ * @param key the key to search for
+ * @param value the value to search for
+ * @return true if the map contains the value
+ */
+ boolean containsMapping(Object key, Object value);
+
/**
* Checks whether the map contains at least one mapping for the specified value.
*
@@ -93,13 +113,17 @@ public interface MultiValuedMap<K, V> {
boolean containsValue(Object value);
/**
- * Checks whether the map contains a mapping for the specified key and value.
+ * Returns a {@link Collection} view of the mappings contained in this multivalued map.
+ * <p>
+ * The collection is backed by the map, so changes to the map are reflected
+ * in the collection, and vice-versa.
+ * </p>
*
- * @param key the key to search for
- * @param value the value to search for
- * @return true if the map contains the value
+ * @return a set view of the mappings contained in this map
*/
- boolean containsMapping(Object key, Object value);
+ Collection<Entry<K, V>> entries();
+
+ // Modification operations
/**
* Returns a view collection of the values associated with the specified key.
@@ -116,7 +140,58 @@ public interface MultiValuedMap<K, V> {
*/
Collection<V> get(K key);
- // Modification operations
+ /**
+ * Returns {@code true} if this map contains no key-value mappings.
+ *
+ * @return {@code true} if this map contains no key-value mappings
+ */
+ boolean isEmpty();
+
+ /**
+ * Returns a {@link MultiSet} view of the keys contained in this multivalued map.
+ * <p>
+ * The {@link MultiSet#getCount(Object)} method of the returned multiset will give
+ * the same result a calling {@code get(Object).size()} for the same key.
+ * </p>
+ * <p>
+ * This multiset is backed by the map, so any changes in the map are reflected in
+ * the multiset.
+ * </p>
+ *
+ * @return a multiset view of the keys contained in this map
+ */
+ MultiSet<K> keys();
+
+ /**
+ * Returns a {@link Set} view of the keys contained in this multivalued map.
+ * <p>
+ * The set is backed by the map, so changes to the map are reflected
+ * in the set, and vice-versa.
+ * </p>
+ * <p>
+ * If the map is modified while an iteration over the set is in
+ * progress (except through the iterator's own {@code remove} operation),
+ * the result of the iteration is undefined. The set supports element
+ * removal, which removes the corresponding mapping from the map, via the
+ * {@code Iterator.remove}, {@code Set.remove}, {@code removeAll},
+ * {@code retainAll}, and {@code clear} operations. It does not support
+ * the {@code add} or {@code addAll} operations.
+ * </p>
+ *
+ * @return a set view of the keys contained in this map
+ */
+ Set<K> keySet();
+
+ /**
+ * Obtains a {@code MapIterator} over this multivalued map.
+ * <p>
+ * A map iterator is an efficient way of iterating over maps. There is no
+ * need to access the entries collection or use {@code Map.Entry} objects.
+ * </p>
+ *
+ * @return a map iterator
+ */
+ MapIterator<K, V> mapIterator();
/**
* Adds a key-value mapping to this multivalued map.
@@ -156,6 +231,8 @@ public interface MultiValuedMap<K, V> {
*/
boolean putAll(K key, Iterable<? extends V> values);
+ // Views
+
/**
* Copies all mappings from the specified map to this multivalued map
* (optional operation).
@@ -241,62 +318,15 @@ public interface MultiValuedMap<K, V> {
boolean removeMapping(Object key, Object item);
/**
- * Removes all of the mappings from this map (optional operation).
- * <p>
- * The map will be empty after this call returns.
- * </p>
- *
- * @throws UnsupportedOperationException if the map is unmodifiable
- */
- void clear();
-
- // Views
-
- /**
- * Returns a {@link Collection} view of the mappings contained in this multivalued map.
- * <p>
- * The collection is backed by the map, so changes to the map are reflected
- * in the collection, and vice-versa.
- * </p>
- *
- * @return a set view of the mappings contained in this map
- */
- Collection<Entry<K, V>> entries();
-
- /**
- * Returns a {@link MultiSet} view of the keys contained in this multivalued map.
- * <p>
- * The {@link MultiSet#getCount(Object)} method of the returned multiset will give
- * the same result a calling {@code get(Object).size()} for the same key.
- * </p>
- * <p>
- * This multiset is backed by the map, so any changes in the map are reflected in
- * the multiset.
- * </p>
- *
- * @return a multiset view of the keys contained in this map
- */
- MultiSet<K> keys();
-
- /**
- * Returns a {@link Set} view of the keys contained in this multivalued map.
- * <p>
- * The set is backed by the map, so changes to the map are reflected
- * in the set, and vice-versa.
- * </p>
+ * Gets the total size of the map.
* <p>
- * If the map is modified while an iteration over the set is in
- * progress (except through the iterator's own {@code remove} operation),
- * the result of the iteration is undefined. The set supports element
- * removal, which removes the corresponding mapping from the map, via the
- * {@code Iterator.remove}, {@code Set.remove}, {@code removeAll},
- * {@code retainAll}, and {@code clear} operations. It does not support
- * the {@code add} or {@code addAll} operations.
+ * Implementations would return the total size of the map which is the count
+ * of the values from all keys.
* </p>
*
- * @return a set view of the keys contained in this map
+ * @return the total size of the map
*/
- Set<K> keySet();
+ int size();
/**
* Gets a {@link Collection} view of all values contained in this multivalued map.
@@ -309,34 +339,4 @@ public interface MultiValuedMap<K, V> {
*/
Collection<V> values();
- /**
- * Returns a view of this multivalued map as a {@code Map} from each distinct
- * key to the non-empty collection of that key's associated values.
- * <p>
- * Note that {@code this.asMap().get(k)} is equivalent to {@code this.get(k)}
- * only when {@code k} is a key contained in the multivalued map; otherwise it
- * returns {@code null} as opposed to an empty collection.
- * </p>
- * <p>
- * Changes to the returned map or the collections that serve as its values
- * will update the underlying multivalued map, and vice versa. The map does
- * not support {@code put} or {@code putAll}, nor do its entries support
- * {@link java.util.Map.Entry#setValue(Object) setValue}.
- * </p>
- *
- * @return a map view of the mappings in this multivalued map
- */
- Map<K, Collection<V>> asMap();
-
- /**
- * Obtains a {@code MapIterator} over this multivalued map.
- * <p>
- * A map iterator is an efficient way of iterating over maps. There is no
- * need to access the entries collection or use {@code Map.Entry} objects.
- * </p>
- *
- * @return a map iterator
- */
- MapIterator<K, V> mapIterator();
-
}
diff --git a/src/main/java/org/apache/commons/collections4/OrderedMap.java b/src/main/java/org/apache/commons/collections4/OrderedMap.java
index 94688b539..b6f292eb7 100644
--- a/src/main/java/org/apache/commons/collections4/OrderedMap.java
+++ b/src/main/java/org/apache/commons/collections4/OrderedMap.java
@@ -27,17 +27,6 @@ package org.apache.commons.collections4;
*/
public interface OrderedMap<K, V> extends IterableMap<K, V> {
- /**
- * Obtains an {@code OrderedMapIterator} over the map.
- * <p>
- * An ordered map iterator is an efficient way of iterating over maps
- * in both directions.
- *
- * @return a map iterator
- */
- @Override
- OrderedMapIterator<K, V> mapIterator();
-
/**
* Gets the first key currently in this map.
*
@@ -54,6 +43,17 @@ public interface OrderedMap<K, V> extends IterableMap<K, V> {
*/
K lastKey();
+ /**
+ * Obtains an {@code OrderedMapIterator} over the map.
+ * <p>
+ * An ordered map iterator is an efficient way of iterating over maps
+ * in both directions.
+ *
+ * @return a map iterator
+ */
+ @Override
+ OrderedMapIterator<K, V> mapIterator();
+
/**
* Gets the next key after the one specified.
*
diff --git a/src/main/java/org/apache/commons/collections4/PredicateUtils.java b/src/main/java/org/apache/commons/collections4/PredicateUtils.java
index 7e1bcbb2d..f5cec7ef1 100644
--- a/src/main/java/org/apache/commons/collections4/PredicateUtils.java
+++ b/src/main/java/org/apache/commons/collections4/PredicateUtils.java
@@ -71,64 +71,116 @@ import org.apache.commons.collections4.functors.UniquePredicate;
public class PredicateUtils {
/**
- * Don't allow instances.
+ * Create a new Predicate that returns true only if all of the specified
+ * predicates are true. The predicates are checked in iterator order.
+ * If the collection of predicates is empty, then this predicate returns true.
+ *
+ * @param <T> the type that the predicate queries
+ * @param predicates a collection of predicates to check, may not be null
+ * @return the {@code all} predicate
+ * @throws NullPointerException if the predicates collection is null
+ * @throws NullPointerException if any predicate in the collection is null
+ * @see AllPredicate
*/
- private PredicateUtils() {}
+ public static <T> Predicate<T> allPredicate(final Collection<? extends Predicate<? super T>> predicates) {
+ return AllPredicate.allPredicate(predicates);
+ }
/**
- * Gets a Predicate that always throws an exception.
- * This could be useful during testing as a placeholder.
+ * Create a new Predicate that returns true only if all of the specified
+ * predicates are true.
+ * If the array of predicates is empty, then this predicate returns true.
*
* @param <T> the type that the predicate queries
- * @return the predicate
- * @see ExceptionPredicate
+ * @param predicates an array of predicates to check, may not be null
+ * @return the {@code all} predicate
+ * @throws NullPointerException if the predicates array is null
+ * @throws NullPointerException if any predicate in the array is null
+ * @see AllPredicate
*/
- public static <T> Predicate<T> exceptionPredicate() {
- return ExceptionPredicate.exceptionPredicate();
+ public static <T> Predicate<T> allPredicate(final Predicate<? super T>... predicates) {
+ return AllPredicate.allPredicate(predicates);
}
/**
- * Gets a Predicate that always returns true.
+ * Create a new Predicate that returns true only if both of the specified
+ * predicates are true.
*
* @param <T> the type that the predicate queries
- * @return the predicate
- * @see TruePredicate
+ * @param predicate1 the first predicate, may not be null
+ * @param predicate2 the second predicate, may not be null
+ * @return the {@code and} predicate
+ * @throws NullPointerException if either predicate is null
+ * @see AndPredicate
*/
- public static <T> Predicate<T> truePredicate() {
- return TruePredicate.truePredicate();
+ public static <T> Predicate<T> andPredicate(final Predicate<? super T> predicate1,
+ final Predicate<? super T> predicate2) {
+ return AndPredicate.andPredicate(predicate1, predicate2);
}
/**
- * Gets a Predicate that always returns false.
+ * Create a new Predicate that returns true if any of the specified
+ * predicates are true. The predicates are checked in iterator order.
+ * If the collection of predicates is empty, then this predicate returns false.
*
* @param <T> the type that the predicate queries
- * @return the predicate
- * @see FalsePredicate
+ * @param predicates a collection of predicates to check, may not be null
+ * @return the {@code any} predicate
+ * @throws NullPointerException if the predicates collection is null
+ * @throws NullPointerException if any predicate in the collection is null
+ * @see AnyPredicate
*/
- public static <T> Predicate<T> falsePredicate() {
- return FalsePredicate.falsePredicate();
+ public static <T> Predicate<T> anyPredicate(final Collection<? extends Predicate<? super T>> predicates) {
+ return AnyPredicate.anyPredicate(predicates);
}
/**
- * Gets a Predicate that checks if the input object passed in is null.
+ * Create a new Predicate that returns true if any of the specified
+ * predicates are true.
+ * If the array of predicates is empty, then this predicate returns false.
*
* @param <T> the type that the predicate queries
- * @return the predicate
- * @see NullPredicate
+ * @param predicates an array of predicates to check, may not be null
+ * @return the {@code any} predicate
+ * @throws NullPointerException if the predicates array is null
+ * @throws NullPointerException if any predicate in the array is null
+ * @see AnyPredicate
*/
- public static <T> Predicate<T> nullPredicate() {
- return NullPredicate.nullPredicate();
+ public static <T> Predicate<T> anyPredicate(final Predicate<? super T>... predicates) {
+ return AnyPredicate.anyPredicate(predicates);
}
/**
- * Gets a Predicate that checks if the input object passed in is not null.
+ * Create a new Predicate that wraps a Transformer. The Transformer must
+ * return either {@link Boolean#TRUE} or {@link Boolean#FALSE} otherwise a
+ * PredicateException will be thrown.
*
* @param <T> the type that the predicate queries
- * @return the predicate
- * @see NotNullPredicate
+ * @param transformer the transformer to wrap, may not be null
+ * @return the transformer wrapping predicate
+ * @throws NullPointerException if the transformer is null
+ * @see TransformerPredicate
*/
- public static <T> Predicate<T> notNullPredicate() {
- return NotNullPredicate.notNullPredicate();
+ public static <T> Predicate<T> asPredicate(final Transformer<? super T, Boolean> transformer) {
+ return TransformerPredicate.transformerPredicate(transformer);
+ }
+
+ /**
+ * Create a new Predicate that returns true if one, but not both, of the
+ * specified predicates are true. XOR
+ *
+ * @param <T> the type that the predicate queries
+ * @param predicate1 the first predicate, may not be null
+ * @param predicate2 the second predicate, may not be null
+ * @return the {@code either} predicate
+ * @throws NullPointerException if either predicate is null
+ * @see OnePredicate
+ */
+ public static <T> Predicate<T> eitherPredicate(final Predicate<? super T> predicate1,
+ final Predicate<? super T> predicate2) {
+ @SuppressWarnings("unchecked")
+ final Predicate<T> onePredicate = PredicateUtils.onePredicate(predicate1, predicate2);
+ return onePredicate;
}
/**
@@ -144,6 +196,29 @@ public class PredicateUtils {
return EqualPredicate.equalPredicate(value);
}
+ /**
+ * Gets a Predicate that always throws an exception.
+ * This could be useful during testing as a placeholder.
+ *
+ * @param <T> the type that the predicate queries
+ * @return the predicate
+ * @see ExceptionPredicate
+ */
+ public static <T> Predicate<T> exceptionPredicate() {
+ return ExceptionPredicate.exceptionPredicate();
+ }
+
+ /**
+ * Gets a Predicate that always returns false.
+ *
+ * @param <T> the type that the predicate queries
+ * @return the predicate
+ * @see FalsePredicate
+ */
+ public static <T> Predicate<T> falsePredicate() {
+ return FalsePredicate.falsePredicate();
+ }
+
/**
* Creates a Predicate that checks if the input object is equal to the
* specified object by identity.
@@ -171,22 +246,6 @@ public class PredicateUtils {
return InstanceofPredicate.instanceOfPredicate(type);
}
... 97196 lines suppressed ...