[COLLECTIONS-589] Add null-safe MapUtils.size(Map<?, ?>) method.

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/collections/trunk@1744808 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Gary D. Gregory 2016-05-20 22:30:06 +00:00
parent 64c5aec863
commit 930015a137
3 changed files with 35 additions and 2 deletions

View File

@ -20,7 +20,10 @@
<title>Commons Collections Changes</title>
</properties>
<body>
<release version="4.2" date="YYYY-MM-DD" description="">
<release version="4.2" date="YYYY-MM-DD" description="New features">
<action issue="COLLECTIONS-589" dev="ggregory" type="add" due-to="Gary Gregory">
Add null-safe MapUtils.size(Map&lt;?, ?>) method.
</action>
</release>
<release version="4.1" date="2015-11-28" description="This is a security and minor release.">
<action issue="COLLECTIONS-508" dev="tn" type="add">

View File

@ -1794,4 +1794,13 @@ public class MapUtils {
new AbstractSortedMapDecorator<K, V>(sortedMap) {};
}
/**
* Gets the given map size or 0 if the map is null
* @param map a Map or null
* @return the given map size or 0 if the map is null
*/
public static int size(Map<?, ?> map) {
return map == null ? 0 : map.size();
}
}

View File

@ -16,7 +16,11 @@
*/
package org.apache.commons.collections4;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
@ -890,4 +894,21 @@ public class MapUtilsTest {
assertSame(iMap, MapUtils.iterableMap(iMap));
}
@Test
public void testSize0() {
assertEquals(0, MapUtils.size(new HashMap<Object, Object>()));
}
@Test
public void testSizeNull() {
assertEquals(0, MapUtils.size(null));
}
@Test
public void testSize() {
final HashMap<Object, Object> map = new HashMap<Object, Object>();
map.put("A", "1");
map.put("B", "2");
assertEquals(2, MapUtils.size(map));
}
}