[COLLECTIONS-551] First bunch of methods which take an Iterable/Iterator/Enumeration as input shall be moved to the appropriate Util classes. Mark existing methods in CollectionUtils as deprecated.

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/collections/trunk@1683009 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Thomas Neidhart 2015-06-01 21:53:01 +00:00
parent 2eb1586bf7
commit d684f950c4
8 changed files with 342 additions and 109 deletions

View File

@ -806,7 +806,7 @@ public class CollectionUtils {
* @param transformer the transformer to perform, may be null * @param transformer the transformer to perform, may be null
*/ */
public static <C> void transform(final Collection<C> collection, public static <C> void transform(final Collection<C> collection,
final Transformer<? super C, ? extends C> transformer) { final Transformer<? super C, ? extends C> transformer) {
if (collection != null && transformer != null) { if (collection != null && transformer != null) {
if (collection instanceof List<?>) { if (collection instanceof List<?>) {
@ -832,17 +832,11 @@ public class CollectionUtils {
* @param input the {@link Iterable} to get the input from, may be null * @param input the {@link Iterable} to get the input from, may be null
* @param predicate the predicate to use, may be null * @param predicate the predicate to use, may be null
* @return the number of matches for the predicate in the collection * @return the number of matches for the predicate in the collection
* @deprecated since 4.1, use {@link IterableUtils#frequency(Iterable, Predicate)} instead
*/ */
@Deprecated
public static <C> int countMatches(final Iterable<C> input, final Predicate<? super C> predicate) { public static <C> int countMatches(final Iterable<C> input, final Predicate<? super C> predicate) {
int count = 0; return predicate == null ? 0 : (int) IterableUtils.frequency(input, predicate);
if (input != null && predicate != null) {
for (final C o : input) {
if (predicate.evaluate(o)) {
count++;
}
}
}
return count;
} }
/** /**
@ -855,16 +849,11 @@ public class CollectionUtils {
* @param input the {@link Iterable} to get the input from, may be null * @param input the {@link Iterable} to get the input from, may be null
* @param predicate the predicate to use, 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 * @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 <C> boolean exists(final Iterable<C> input, final Predicate<? super C> predicate) { public static <C> boolean exists(final Iterable<C> input, final Predicate<? super C> predicate) {
if (input != null && predicate != null) { return predicate == null ? false : IterableUtils.matchesAny(input, predicate);
for (final C o : input) {
if (predicate.evaluate(o)) {
return true;
}
}
}
return false;
} }
/** /**
@ -880,20 +869,11 @@ public class CollectionUtils {
* @return true if every element of the collection matches the predicate or if the * @return true if every element of the collection matches the predicate or if the
* collection is empty, false otherwise * collection is empty, false otherwise
* @since 4.0 * @since 4.0
* @deprecated since 4.1, use {@link IterableUtils#matchesAll(Iterable, Predicate)} instead
*/ */
@Deprecated
public static <C> boolean matchesAll(final Iterable<C> input, final Predicate<? super C> predicate) { public static <C> boolean matchesAll(final Iterable<C> input, final Predicate<? super C> predicate) {
if (predicate == null) { return predicate == null ? false : IterableUtils.matchesAll(input, predicate);
return false;
}
if (input != null) {
for (final C o : input) {
if (!predicate.evaluate(o)) {
return false;
}
}
}
return true;
} }
/** /**
@ -909,7 +889,7 @@ public class CollectionUtils {
* @throws NullPointerException if the input collection is null * @throws NullPointerException if the input collection is null
*/ */
public static <O> Collection<O> select(final Iterable<? extends O> inputCollection, public static <O> Collection<O> select(final Iterable<? extends O> inputCollection,
final Predicate<? super O> predicate) { final Predicate<? super O> predicate) {
final Collection<O> answer = inputCollection instanceof Collection<?> ? final Collection<O> answer = inputCollection instanceof Collection<?> ?
new ArrayList<O>(((Collection<?>) inputCollection).size()) : new ArrayList<O>(); new ArrayList<O>(((Collection<?>) inputCollection).size()) : new ArrayList<O>();
return select(inputCollection, predicate, answer); return select(inputCollection, predicate, answer);
@ -957,7 +937,7 @@ public class CollectionUtils {
* @throws NullPointerException if the input collection is null * @throws NullPointerException if the input collection is null
*/ */
public static <O> Collection<O> selectRejected(final Iterable<? extends O> inputCollection, public static <O> Collection<O> selectRejected(final Iterable<? extends O> inputCollection,
final Predicate<? super O> predicate) { final Predicate<? super O> predicate) {
final Collection<O> answer = inputCollection instanceof Collection<?> ? final Collection<O> answer = inputCollection instanceof Collection<?> ?
new ArrayList<O>(((Collection<?>) inputCollection).size()) : new ArrayList<O>(); new ArrayList<O>(((Collection<?>) inputCollection).size()) : new ArrayList<O>();
return selectRejected(inputCollection, predicate, answer); return selectRejected(inputCollection, predicate, answer);
@ -1020,7 +1000,7 @@ public class CollectionUtils {
* @since 4.1 * @since 4.1
*/ */
public static <O> List<List<O>> partition(final Iterable<? extends O> inputCollection, public static <O> List<List<O>> partition(final Iterable<? extends O> inputCollection,
final Predicate<? super O> predicate) { final Predicate<? super O> predicate) {
@SuppressWarnings({ "unchecked", "rawtypes" }) // safe @SuppressWarnings({ "unchecked", "rawtypes" }) // safe
final Factory<List<O>> factory = FactoryUtils.instantiateFactory((Class) ArrayList.class); final Factory<List<O>> factory = FactoryUtils.instantiateFactory((Class) ArrayList.class);
@ -1103,7 +1083,7 @@ public class CollectionUtils {
* @since 4.1 * @since 4.1
*/ */
public static <O> List<List<O>> partition(final Iterable<? extends O> inputCollection, public static <O> List<List<O>> partition(final Iterable<? extends O> inputCollection,
final Predicate<? super O>... predicates) { final Predicate<? super O>... predicates) {
@SuppressWarnings({ "unchecked", "rawtypes" }) // safe @SuppressWarnings({ "unchecked", "rawtypes" }) // safe
final Factory<List<O>> factory = FactoryUtils.instantiateFactory((Class) ArrayList.class); final Factory<List<O>> factory = FactoryUtils.instantiateFactory((Class) ArrayList.class);
@ -1391,35 +1371,6 @@ public class CollectionUtils {
return IteratorUtils.get(iterator, index); return IteratorUtils.get(iterator, index);
} }
/**
* Returns the <code>index</code>-th value in the {@link Enumeration}, throwing
* <code>IndexOutOfBoundsException</code> if there is no such element.
* <p>
* The Enumeration is advanced to <code>index</code> (or to the end, if
* <code>index</code> exceeds the number of entries) as a side effect of this method.
*
* @param e the enumeration to get a value from
* @param index the index to get
* @param <T> the type of object in the {@link Enumeration}
* @return the object at the specified index
* @throws IndexOutOfBoundsException if the index is invalid
* @throws IllegalArgumentException if the object type is invalid
* @since 4.1
*/
public static <T> T get(final Enumeration<T> e, final int index) {
int i = index;
checkIndexBounds(i);
while (e.hasMoreElements()) {
i--;
if (i == -1) {
return e.nextElement();
} else {
e.nextElement();
}
}
throw new IndexOutOfBoundsException("Entry does not exist: " + i);
}
/** /**
* Ensures an index is not negative. * Ensures an index is not negative.
* @param index the index to check. * @param index the index to check.
@ -1487,18 +1438,21 @@ public class CollectionUtils {
if (object instanceof Map<?,?>) { if (object instanceof Map<?,?>) {
final Map<?, ?> map = (Map<?, ?>) object; final Map<?, ?> map = (Map<?, ?>) object;
final Iterator<?> iterator = map.entrySet().iterator(); final Iterator<?> iterator = map.entrySet().iterator();
return get(iterator, i); return IteratorUtils.get(iterator, i);
} else if (object instanceof Object[]) { } else if (object instanceof Object[]) {
return ((Object[]) object)[i]; return ((Object[]) object)[i];
} else if (object instanceof Iterator<?>) { } else if (object instanceof Iterator<?>) {
final Iterator<?> it = (Iterator<?>) object; final Iterator<?> it = (Iterator<?>) object;
return get(it, i); return IteratorUtils.get(it, i);
} else if (object instanceof Iterable<?>) {
final Iterable<?> iterable = (Iterable<?>) object;
return IterableUtils.get(iterable, i);
} else if (object instanceof Collection<?>) { } else if (object instanceof Collection<?>) {
final Iterator<?> iterator = ((Collection<?>) object).iterator(); final Iterator<?> iterator = ((Collection<?>) object).iterator();
return get(iterator, i); return IteratorUtils.get(iterator, i);
} else if (object instanceof Enumeration<?>) { } else if (object instanceof Enumeration<?>) {
final Enumeration<?> it = (Enumeration<?>) object; final Enumeration<?> it = (Enumeration<?>) object;
return get(it, i); return EnumerationUtils.get(it, i);
} else if (object == null) { } else if (object == null) {
throw new IllegalArgumentException("Unsupported object type: null"); throw new IllegalArgumentException("Unsupported object type: null");
} else { } else {
@ -1552,14 +1506,12 @@ public class CollectionUtils {
total = ((Map<?, ?>) object).size(); total = ((Map<?, ?>) object).size();
} else if (object instanceof Collection<?>) { } else if (object instanceof Collection<?>) {
total = ((Collection<?>) object).size(); total = ((Collection<?>) object).size();
} else if (object instanceof Iterable<?>) {
total = IterableUtils.size((Iterable<?>) object);
} else if (object instanceof Object[]) { } else if (object instanceof Object[]) {
total = ((Object[]) object).length; total = ((Object[]) object).length;
} else if (object instanceof Iterator<?>) { } else if (object instanceof Iterator<?>) {
final Iterator<?> it = (Iterator<?>) object; total = IteratorUtils.size((Iterator<?>) object);
while (it.hasNext()) {
total++;
it.next();
}
} else if (object instanceof Enumeration<?>) { } else if (object instanceof Enumeration<?>) {
final Enumeration<?> it = (Enumeration<?>) object; final Enumeration<?> it = (Enumeration<?>) object;
while (it.hasMoreElements()) { while (it.hasMoreElements()) {
@ -1601,6 +1553,8 @@ public class CollectionUtils {
return true; return true;
} else if (object instanceof Collection<?>) { } else if (object instanceof Collection<?>) {
return ((Collection<?>) object).isEmpty(); return ((Collection<?>) object).isEmpty();
} else if (object instanceof Iterable<?>) {
return IterableUtils.isEmpty((Iterable<?>) object);
} else if (object instanceof Map<?, ?>) { } else if (object instanceof Map<?, ?>) {
return ((Map<?, ?>) object).isEmpty(); return ((Map<?, ?>) object).isEmpty();
} else if (object instanceof Object[]) { } else if (object instanceof Object[]) {
@ -2031,7 +1985,7 @@ public class CollectionUtils {
* @since 4.1 * @since 4.1
*/ */
public static <E> boolean contains(final Collection<? extends E> collection, final E object, public static <E> boolean contains(final Collection<? extends E> collection, final E object,
final Equator<? super E> equator) { final Equator<? super E> equator) {
for (final E obj : collection) { for (final E obj : collection) {
if (equator.equate(obj, object)) { if (equator.equate(obj, object)) {
return true; return true;

View File

@ -36,6 +36,35 @@ public class EnumerationUtils {
*/ */
private EnumerationUtils() {} private EnumerationUtils() {}
/**
* Returns the <code>index</code>-th value in the {@link Enumeration}, throwing
* <code>IndexOutOfBoundsException</code> if there is no such element.
* <p>
* The Enumeration is advanced to <code>index</code> (or to the end, if
* <code>index</code> exceeds the number of entries) as a side effect of this method.
*
* @param e the enumeration to get a value from
* @param index the index to get
* @param <T> the type of object in the {@link Enumeration}
* @return the object at the specified index
* @throws IndexOutOfBoundsException if the index is invalid
* @throws IllegalArgumentException if the object type is invalid
* @since 4.1
*/
public static <T> T get(final Enumeration<T> e, final int index) {
int i = index;
CollectionUtils.checkIndexBounds(i);
while (e.hasMoreElements()) {
i--;
if (i == -1) {
return e.nextElement();
} else {
e.nextElement();
}
}
throw new IndexOutOfBoundsException("Entry does not exist: " + i);
}
/** /**
* Creates a list based on an enumeration. * Creates a list based on an enumeration.
* *

View File

@ -28,6 +28,11 @@ import org.apache.commons.collections4.iterators.ZippingIterator;
/** /**
* Provides utility methods and decorators for {@link Iterable} instances. * Provides utility methods and decorators for {@link Iterable} instances.
* <p>
* <b>Note</b>: by design, all provided utility methods will treat a {@code null}
* {@link Iterable} parameters the same way as an empty iterable. All other required
* parameters which are null, e.g. a {@link Predicate}, will result in a
* {@link NullPointerException}.
* *
* @since 4.1 * @since 4.1
* @version $Id$ * @version $Id$
@ -487,6 +492,32 @@ public class IterableUtils {
return IteratorUtils.matchesAny(emptyIteratorIfNull(iterable), predicate); return IteratorUtils.matchesAny(emptyIteratorIfNull(iterable), predicate);
} }
/**
* Counts the number of elements in the input iterable that match the predicate.
* <p>
* A <code>null</code> 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 frequency(final Iterable<E> input, final Predicate<? super E> predicate) {
if (predicate == null) {
throw new NullPointerException("Predicate must not be null.");
}
long count = 0;
if (input != null) {
for (final E o : input) {
if (predicate.evaluate(o)) {
count++;
}
}
}
return count;
}
/** /**
* Answers true if the provided iterable is empty. * Answers true if the provided iterable is empty.
* <p> * <p>

View File

@ -927,7 +927,8 @@ public class IteratorUtils {
* @throws IllegalArgumentException if any iterator is null * @throws IllegalArgumentException if any iterator is null
* @since 4.1 * @since 4.1
*/ */
public static <E> ZippingIterator<E> zippingIterator(final Iterator<? extends E> a, final Iterator<? extends E> b) { public static <E> ZippingIterator<E> zippingIterator(final Iterator<? extends E> a,
final Iterator<? extends E> b) {
return new ZippingIterator<E>(a, b); return new ZippingIterator<E>(a, b);
} }
@ -1176,8 +1177,8 @@ public class IteratorUtils {
if (obj instanceof Iterator) { if (obj instanceof Iterator) {
return (Iterator<?>) obj; return (Iterator<?>) obj;
} }
if (obj instanceof Collection) { if (obj instanceof Iterable) {
return ((Collection<?>) obj).iterator(); return ((Iterable<?>) obj).iterator();
} }
if (obj instanceof Object[]) { if (obj instanceof Object[]) {
return new ObjectArrayIterator<Object>((Object[]) obj); return new ObjectArrayIterator<Object>((Object[]) obj);

View File

@ -785,6 +785,7 @@ public class CollectionUtilsTest extends MockTestCase {
} }
@Test @Test
@Deprecated
public void getFromIterator() throws Exception { public void getFromIterator() throws Exception {
// Iterator, entry exists // Iterator, entry exists
Iterator<Integer> iterator = iterableA.iterator(); Iterator<Integer> iterator = iterableA.iterator();
@ -803,6 +804,7 @@ public class CollectionUtilsTest extends MockTestCase {
} }
@Test @Test
@Deprecated
public void getFromEnumeration() throws Exception { public void getFromEnumeration() throws Exception {
// Enumeration, entry exists // Enumeration, entry exists
final Vector<String> vector = new Vector<String>(); final Vector<String> vector = new Vector<String>();
@ -824,6 +826,7 @@ public class CollectionUtilsTest extends MockTestCase {
} }
@Test(expected = IndexOutOfBoundsException.class) @Test(expected = IndexOutOfBoundsException.class)
@Deprecated
public void getFromIterable() throws Exception { public void getFromIterable() throws Exception {
// Collection, entry exists // Collection, entry exists
final Bag<String> bag = new HashBag<String>(); final Bag<String> bag = new HashBag<String>();
@ -849,7 +852,7 @@ public class CollectionUtilsTest extends MockTestCase {
} }
@Test(expected = IndexOutOfBoundsException.class) @Test(expected = IndexOutOfBoundsException.class)
public void getFromPrimativeArray() throws Exception { public void getFromPrimitiveArray() throws Exception {
// Primitive array, entry exists // Primitive array, entry exists
final int[] array = new int[2]; final int[] array = new int[2];
array[0] = 10; array[0] = 10;
@ -1126,6 +1129,7 @@ public class CollectionUtilsTest extends MockTestCase {
} }
@Test @Test
@Deprecated
public void countMatches() { public void countMatches() {
assertEquals(4, CollectionUtils.countMatches(iterableB, EQUALS_TWO)); assertEquals(4, CollectionUtils.countMatches(iterableB, EQUALS_TWO));
assertEquals(0, CollectionUtils.countMatches(iterableA, null)); assertEquals(0, CollectionUtils.countMatches(iterableA, null));
@ -1134,6 +1138,7 @@ public class CollectionUtilsTest extends MockTestCase {
} }
@Test @Test
@Deprecated
public void exists() { public void exists() {
final List<Integer> list = new ArrayList<Integer>(); final List<Integer> list = new ArrayList<Integer>();
assertFalse(CollectionUtils.exists(null, null)); assertFalse(CollectionUtils.exists(null, null));
@ -1834,6 +1839,7 @@ public class CollectionUtilsTest extends MockTestCase {
} }
@Test @Test
@Deprecated
public void testMatchesAll() { public void testMatchesAll() {
assertFalse(CollectionUtils.matchesAll(null, null)); assertFalse(CollectionUtils.matchesAll(null, null));
assertFalse(CollectionUtils.matchesAll(collectionA, null)); assertFalse(CollectionUtils.matchesAll(collectionA, null));

View File

@ -16,26 +16,29 @@
*/ */
package org.apache.commons.collections4; package org.apache.commons.collections4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.List; import java.util.List;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import java.util.Vector;
import junit.framework.Test; import org.junit.Test;
/** /**
* Tests EnumerationUtils. * Tests EnumerationUtils.
* *
* @version $Id$ * @version $Id$
*/ */
public class EnumerationUtilsTest extends BulkTest { public class EnumerationUtilsTest {
public EnumerationUtilsTest(final String name) {
super(name);
}
public static final String TO_LIST_FIXTURE = "this is a test"; public static final String TO_LIST_FIXTURE = "this is a test";
@Test
public void testToListWithStringTokenizer() { public void testToListWithStringTokenizer() {
final List<String> expectedList1 = new ArrayList<String>(); final List<String> expectedList1 = new ArrayList<String>();
final StringTokenizer st = new StringTokenizer(TO_LIST_FIXTURE); final StringTokenizer st = new StringTokenizer(TO_LIST_FIXTURE);
@ -53,6 +56,7 @@ public class EnumerationUtilsTest extends BulkTest {
assertEquals(expectedList2, actualList); assertEquals(expectedList2, actualList);
} }
@Test
public void testToListWithHashtable() { public void testToListWithHashtable() {
final Hashtable<String, Integer> expected = new Hashtable<String, Integer>(); final Hashtable<String, Integer> expected = new Hashtable<String, Integer>();
expected.put("one", Integer.valueOf(1)); expected.put("one", Integer.valueOf(1));
@ -83,8 +87,25 @@ public class EnumerationUtilsTest extends BulkTest {
assertTrue(actualKeyList.containsAll(expectedKeyList)); assertTrue(actualKeyList.containsAll(expectedKeyList));
} }
public static Test suite() { @Test
return BulkTest.makeSuite(EnumerationUtilsTest.class); public void getFromEnumeration() throws Exception {
// Enumeration, entry exists
final Vector<String> vector = new Vector<String>();
vector.addElement("zero");
vector.addElement("one");
Enumeration<String> en = vector.elements();
assertEquals("zero", EnumerationUtils.get(en, 0));
en = vector.elements();
assertEquals("one", EnumerationUtils.get(en, 1));
// Enumerator, non-existent entry
try {
EnumerationUtils.get(en, 3);
fail("Expecting IndexOutOfBoundsException.");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertTrue(!en.hasMoreElements());
} }
} }

View File

@ -16,10 +16,20 @@
*/ */
package org.apache.commons.collections4; package org.apache.commons.collections4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import junit.framework.Test; import org.apache.commons.collections4.bag.HashBag;
import org.junit.Before;
import org.junit.Test;
/** /**
* Tests for IterableUtils. * Tests for IterableUtils.
@ -27,22 +37,24 @@ import junit.framework.Test;
* @since 4.1 * @since 4.1
* @version $Id$ * @version $Id$
*/ */
public class IterableUtilsTest extends BulkTest { public class IterableUtilsTest {
/** /**
* Iterable of {@link Integer}s * Iterable of {@link Integer}s
*/ */
private Iterable<Integer> iterableA = null; private Iterable<Integer> iterableA = null;
public IterableUtilsTest(final String name) { /**
super(name); * Iterable of {@link Long}s
} */
private Iterable<Long> iterableB = null;
public static Test suite() {
return BulkTest.makeSuite(IterableUtilsTest.class); /**
} * An empty Iterable.
*/
@Override private Iterable<Integer> emptyIterable = null;
@Before
public void setUp() { public void setUp() {
List<Integer> listA = new ArrayList<Integer>(); List<Integer> listA = new ArrayList<Integer>();
listA.add(1); listA.add(1);
@ -56,8 +68,125 @@ public class IterableUtilsTest extends BulkTest {
listA.add(4); listA.add(4);
listA.add(4); listA.add(4);
iterableA = listA; iterableA = listA;
Collection<Long> collectionB = new LinkedList<Long>();
collectionB.add(5L);
collectionB.add(4L);
collectionB.add(4L);
collectionB.add(3L);
collectionB.add(3L);
collectionB.add(3L);
collectionB.add(2L);
collectionB.add(2L);
collectionB.add(2L);
collectionB.add(2L);
iterableB = collectionB;
emptyIterable = Collections.emptyList();
} }
private static Predicate<Number> EQUALS_TWO = new Predicate<Number>() {
public boolean evaluate(final Number input) {
return input.intValue() == 2;
}
};
// -----------------------------------------------------------------------
@Test
public void frequency() {
assertEquals(4, IterableUtils.frequency(iterableB, EQUALS_TWO));
assertEquals(0, IterableUtils.frequency(null, EQUALS_TWO));
try {
assertEquals(0, IterableUtils.frequency(iterableA, null));
fail("predicate must not be null");
} catch (NullPointerException ex) {
// expected
}
try {
assertEquals(0, IterableUtils.frequency(null, null));
fail("predicate must not be null");
} catch (NullPointerException ex) {
// expected
}
}
@Test
public void matchesAny() {
final List<Integer> list = new ArrayList<Integer>();
try {
assertFalse(IterableUtils.matchesAny(null, null));
fail("predicate must not be null");
} catch (NullPointerException ex) {
// expected
}
try {
assertFalse(IterableUtils.matchesAny(list, null));
fail("predicate must not be null");
} catch (NullPointerException ex) {
// expected
}
assertFalse(IterableUtils.matchesAny(null, EQUALS_TWO));
assertFalse(IterableUtils.matchesAny(list, EQUALS_TWO));
list.add(1);
list.add(3);
list.add(4);
assertFalse(IterableUtils.matchesAny(list, EQUALS_TWO));
list.add(2);
assertEquals(true, IterableUtils.matchesAny(list, EQUALS_TWO));
}
@Test
public void matchesAll() {
try {
assertFalse(IterableUtils.matchesAll(null, null));
fail("predicate must not be null");
} catch (NullPointerException ex) {
// expected
}
try {
assertFalse(IterableUtils.matchesAll(iterableA, null));
fail("predicate must not be null");
} catch (NullPointerException ex) {
// expected
}
Predicate<Integer> lessThanFive = new Predicate<Integer>() {
public boolean evaluate(Integer object) {
return object < 5;
}
};
assertTrue(IterableUtils.matchesAll(iterableA, lessThanFive));
Predicate<Integer> lessThanFour = new Predicate<Integer>() {
public boolean evaluate(Integer object) {
return object < 4;
}
};
assertFalse(IterableUtils.matchesAll(iterableA, lessThanFour));
assertTrue(IterableUtils.matchesAll(null, lessThanFour));
assertTrue(IterableUtils.matchesAll(emptyIterable, lessThanFour));
}
@Test(expected = IndexOutOfBoundsException.class)
public void getFromIterable() throws Exception {
// Collection, entry exists
final Bag<String> bag = new HashBag<String>();
bag.add("element", 1);
assertEquals("element", IterableUtils.get(bag, 0));
// Collection, non-existent entry
IterableUtils.get(bag, 1);
}
@Test
public void testToString() { public void testToString() {
String result = IterableUtils.toString(iterableA); String result = IterableUtils.toString(iterableA);
assertEquals("[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]", result); assertEquals("[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]", result);
@ -91,7 +220,8 @@ public class IterableUtilsTest extends BulkTest {
}); });
assertEquals("[]", result); assertEquals("[]", result);
} }
@Test
public void testToStringDelimiter() { public void testToStringDelimiter() {
Transformer<Integer, String> transformer = new Transformer<Integer, String>() { Transformer<Integer, String> transformer = new Transformer<Integer, String>() {
@ -127,7 +257,8 @@ public class IterableUtilsTest extends BulkTest {
result = IterableUtils.toString(new ArrayList<Integer>(), transformer, "", "", ""); result = IterableUtils.toString(new ArrayList<Integer>(), transformer, "", "", "");
assertEquals("", result); assertEquals("", result);
} }
@Test
public void testToStringWithNullArguments() { public void testToStringWithNullArguments() {
String result = IterableUtils.toString(null, new Transformer<Integer, String>() { String result = IterableUtils.toString(null, new Transformer<Integer, String>() {
public String transform(Integer input) { public String transform(Integer input) {

View File

@ -16,6 +16,12 @@
*/ */
package org.apache.commons.collections4; package org.apache.commons.collections4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Iterator; import java.util.Iterator;
@ -23,13 +29,13 @@ import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import junit.framework.Test;
import org.apache.commons.collections4.iterators.EmptyIterator; import org.apache.commons.collections4.iterators.EmptyIterator;
import org.apache.commons.collections4.iterators.EmptyListIterator; import org.apache.commons.collections4.iterators.EmptyListIterator;
import org.apache.commons.collections4.iterators.EmptyMapIterator; import org.apache.commons.collections4.iterators.EmptyMapIterator;
import org.apache.commons.collections4.iterators.EmptyOrderedIterator; import org.apache.commons.collections4.iterators.EmptyOrderedIterator;
import org.apache.commons.collections4.iterators.EmptyOrderedMapIterator; import org.apache.commons.collections4.iterators.EmptyOrderedMapIterator;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
@ -42,16 +48,33 @@ import static org.easymock.EasyMock.replay;
* *
* @version $Id$ * @version $Id$
*/ */
public class IteratorUtilsTest extends BulkTest { public class IteratorUtilsTest {
public IteratorUtilsTest(final String name) { /**
super(name); * Collection of {@link Integer}s
} */
private List<Integer> collectionA = null;
public static Test suite() {
return BulkTest.makeSuite(IteratorUtilsTest.class); private Iterable<Integer> iterableA = null;
@Before
public void setUp() {
collectionA = new ArrayList<Integer>();
collectionA.add(1);
collectionA.add(2);
collectionA.add(2);
collectionA.add(3);
collectionA.add(3);
collectionA.add(3);
collectionA.add(4);
collectionA.add(4);
collectionA.add(4);
collectionA.add(4);
iterableA = collectionA;
} }
@Test
public void testAsIterable() { public void testAsIterable() {
final List<Integer> list = new ArrayList<Integer>(); final List<Integer> list = new ArrayList<Integer>();
list.add(Integer.valueOf(0)); list.add(Integer.valueOf(0));
@ -72,6 +95,7 @@ public class IteratorUtilsTest extends BulkTest {
assertFalse("should not be able to iterate twice", IteratorUtils.asIterable(iterator).iterator().hasNext()); assertFalse("should not be able to iterate twice", IteratorUtils.asIterable(iterator).iterator().hasNext());
} }
@Test
public void testAsIterableNull() { public void testAsIterableNull() {
try { try {
IteratorUtils.asIterable(null); IteratorUtils.asIterable(null);
@ -81,6 +105,7 @@ public class IteratorUtilsTest extends BulkTest {
} }
} }
@Test
public void testAsMultipleIterable() { public void testAsMultipleIterable() {
final List<Integer> list = new ArrayList<Integer>(); final List<Integer> list = new ArrayList<Integer>();
list.add(Integer.valueOf(0)); list.add(Integer.valueOf(0));
@ -107,6 +132,7 @@ public class IteratorUtilsTest extends BulkTest {
assertTrue(expected > 0); assertTrue(expected > 0);
} }
@Test
public void testAsMultipleIterableNull() { public void testAsMultipleIterableNull() {
try { try {
IteratorUtils.asMultipleUseIterable(null); IteratorUtils.asMultipleUseIterable(null);
@ -116,6 +142,7 @@ public class IteratorUtilsTest extends BulkTest {
} }
} }
@Test
public void testToList() { public void testToList() {
final List<Object> list = new ArrayList<Object>(); final List<Object> list = new ArrayList<Object>();
list.add(Integer.valueOf(1)); list.add(Integer.valueOf(1));
@ -125,6 +152,7 @@ public class IteratorUtilsTest extends BulkTest {
assertEquals(list, result); assertEquals(list, result);
} }
@Test
public void testToArray() { public void testToArray() {
final List<Object> list = new ArrayList<Object>(); final List<Object> list = new ArrayList<Object>();
list.add(Integer.valueOf(1)); list.add(Integer.valueOf(1));
@ -134,6 +162,7 @@ public class IteratorUtilsTest extends BulkTest {
assertEquals(list, Arrays.asList(result)); assertEquals(list, Arrays.asList(result));
} }
@Test
public void testToArray2() { public void testToArray2() {
final List<String> list = new ArrayList<String>(); final List<String> list = new ArrayList<String>();
list.add("One"); list.add("One");
@ -143,6 +172,7 @@ public class IteratorUtilsTest extends BulkTest {
assertEquals(list, Arrays.asList(result)); assertEquals(list, Arrays.asList(result));
} }
@Test
public void testArrayIterator() { public void testArrayIterator() {
final Object[] objArray = {"a", "b", "c"}; final Object[] objArray = {"a", "b", "c"};
ResettableIterator<Object> iterator = IteratorUtils.arrayIterator(objArray); ResettableIterator<Object> iterator = IteratorUtils.arrayIterator(objArray);
@ -263,6 +293,7 @@ public class IteratorUtilsTest extends BulkTest {
} }
} }
@Test
public void testArrayListIterator() { public void testArrayListIterator() {
final Object[] objArray = {"a", "b", "c", "d"}; final Object[] objArray = {"a", "b", "c", "d"};
ResettableListIterator<Object> iterator = IteratorUtils.arrayListIterator(objArray); ResettableListIterator<Object> iterator = IteratorUtils.arrayListIterator(objArray);
@ -454,6 +485,7 @@ public class IteratorUtilsTest extends BulkTest {
/** /**
* Test empty iterator * Test empty iterator
*/ */
@Test
public void testEmptyIterator() { public void testEmptyIterator() {
assertSame(EmptyIterator.INSTANCE, IteratorUtils.EMPTY_ITERATOR); assertSame(EmptyIterator.INSTANCE, IteratorUtils.EMPTY_ITERATOR);
assertSame(EmptyIterator.RESETTABLE_INSTANCE, IteratorUtils.EMPTY_ITERATOR); assertSame(EmptyIterator.RESETTABLE_INSTANCE, IteratorUtils.EMPTY_ITERATOR);
@ -480,6 +512,7 @@ public class IteratorUtilsTest extends BulkTest {
/** /**
* Test empty list iterator * Test empty list iterator
*/ */
@Test
public void testEmptyListIterator() { public void testEmptyListIterator() {
assertSame(EmptyListIterator.INSTANCE, IteratorUtils.EMPTY_LIST_ITERATOR); assertSame(EmptyListIterator.INSTANCE, IteratorUtils.EMPTY_LIST_ITERATOR);
assertSame(EmptyListIterator.RESETTABLE_INSTANCE, IteratorUtils.EMPTY_LIST_ITERATOR); assertSame(EmptyListIterator.RESETTABLE_INSTANCE, IteratorUtils.EMPTY_LIST_ITERATOR);
@ -520,6 +553,7 @@ public class IteratorUtilsTest extends BulkTest {
/** /**
* Test empty map iterator * Test empty map iterator
*/ */
@Test
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testEmptyMapIterator() { public void testEmptyMapIterator() {
assertSame(EmptyMapIterator.INSTANCE, IteratorUtils.EMPTY_MAP_ITERATOR); assertSame(EmptyMapIterator.INSTANCE, IteratorUtils.EMPTY_MAP_ITERATOR);
@ -559,6 +593,7 @@ public class IteratorUtilsTest extends BulkTest {
/** /**
* Test empty map iterator * Test empty map iterator
*/ */
@Test
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testEmptyOrderedIterator() { public void testEmptyOrderedIterator() {
assertSame(EmptyOrderedIterator.INSTANCE, IteratorUtils.EMPTY_ORDERED_ITERATOR); assertSame(EmptyOrderedIterator.INSTANCE, IteratorUtils.EMPTY_ORDERED_ITERATOR);
@ -590,6 +625,7 @@ public class IteratorUtilsTest extends BulkTest {
/** /**
* Test empty map iterator * Test empty map iterator
*/ */
@Test
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testEmptyOrderedMapIterator() { public void testEmptyOrderedMapIterator() {
assertSame(EmptyOrderedMapIterator.INSTANCE, IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR); assertSame(EmptyOrderedMapIterator.INSTANCE, IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR);
@ -633,6 +669,7 @@ public class IteratorUtilsTest extends BulkTest {
/** /**
* Test next() and hasNext() for an immutable Iterator. * Test next() and hasNext() for an immutable Iterator.
*/ */
@Test
public void testUnmodifiableIteratorIteration() { public void testUnmodifiableIteratorIteration() {
final Iterator<String> iterator = getImmutableIterator(); final Iterator<String> iterator = getImmutableIterator();
@ -659,6 +696,7 @@ public class IteratorUtilsTest extends BulkTest {
* Test next(), hasNext(), previous() and hasPrevious() for an immutable * Test next(), hasNext(), previous() and hasPrevious() for an immutable
* ListIterator. * ListIterator.
*/ */
@Test
public void testUnmodifiableListIteratorIteration() { public void testUnmodifiableListIteratorIteration() {
final ListIterator<String> listIterator = getImmutableListIterator(); final ListIterator<String> listIterator = getImmutableListIterator();
@ -709,6 +747,7 @@ public class IteratorUtilsTest extends BulkTest {
/** /**
* Test remove() for an immutable Iterator. * Test remove() for an immutable Iterator.
*/ */
@Test
public void testUnmodifiableIteratorImmutability() { public void testUnmodifiableIteratorImmutability() {
final Iterator<String> iterator = getImmutableIterator(); final Iterator<String> iterator = getImmutableIterator();
@ -735,6 +774,7 @@ public class IteratorUtilsTest extends BulkTest {
/** /**
* Test remove() for an immutable ListIterator. * Test remove() for an immutable ListIterator.
*/ */
@Test
public void testUnmodifiableListIteratorImmutability() { public void testUnmodifiableListIteratorImmutability() {
final ListIterator<String> listIterator = getImmutableListIterator(); final ListIterator<String> listIterator = getImmutableListIterator();
@ -792,6 +832,7 @@ public class IteratorUtilsTest extends BulkTest {
/** /**
* Tests method nodeListIterator(NodeList) * Tests method nodeListIterator(NodeList)
*/ */
@Test
public void testNodeListIterator() { public void testNodeListIterator() {
final Node[] nodes = createNodes(); final Node[] nodes = createNodes();
final NodeList nodeList = createNodeList(nodes); final NodeList nodeList = createNodeList(nodes);
@ -812,6 +853,7 @@ public class IteratorUtilsTest extends BulkTest {
/** /**
* Tests method nodeListIterator(Node) * Tests method nodeListIterator(Node)
*/ */
@Test
public void testNodeIterator() { public void testNodeIterator() {
final Node[] nodes = createNodes(); final Node[] nodes = createNodes();
final NodeList nodeList = createNodeList(nodes); final NodeList nodeList = createNodeList(nodes);
@ -863,4 +905,22 @@ public class IteratorUtilsTest extends BulkTest {
}; };
} }
@Test
public void getFromIterator() throws Exception {
// Iterator, entry exists
Iterator<Integer> iterator = iterableA.iterator();
assertEquals(1, (int) IteratorUtils.get(iterator, 0));
iterator = iterableA.iterator();
assertEquals(2, (int) IteratorUtils.get(iterator, 1));
// Iterator, non-existent entry
try {
IteratorUtils.get(iterator, 10);
fail("Expecting IndexOutOfBoundsException.");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertTrue(!iterator.hasNext());
}
} }