浏览代码

enhance CollUtil.zip

Looly 6 年之前
父节点
当前提交
ac7a6edb25

+ 2 - 0
CHANGELOG.md

@@ -6,6 +6,8 @@
 ## 4.6.3
 
 ### 新特性
+* 【core】        改进CollUtil.zip逻辑,减少内存复制(issue#I10T01@Gitee)
+
 ### Bug修复
 * 【http】         修复HttpRquest中body方法长度计算问题(issue#I10UPG@Gitee)
 

+ 8 - 7
hutool-core/src/main/java/cn/hutool/core/collection/CollUtil.java

@@ -1517,13 +1517,14 @@ public class CollUtil {
 			return null;
 		}
 
-		final List<K> keyList = new ArrayList<K>(keys);
-		final List<V> valueList = new ArrayList<V>(values);
-
-		final int size = Math.min(keys.size(), values.size());
-		final Map<K, V> map = new HashMap<K, V>((int) (size / 0.75));
-		for (int i = 0; i < size; i++) {
-			map.put(keyList.get(i), valueList.get(i));
+		int entryCount = Math.min(keys.size(), values.size());
+		final Map<K, V> map = newHashMap(entryCount);
+		
+		final Iterator<K> keyIterator = keys.iterator();
+		final Iterator<V> valueIterator = values.iterator();
+		while (entryCount > 0) {
+			map.put(keyIterator.next(), valueIterator.next());
+			entryCount--;
 		}
 
 		return map;

+ 19 - 4
hutool-core/src/test/java/cn/hutool/core/collection/CollUtilTest.java

@@ -547,12 +547,12 @@ public class CollUtilTest {
 
 		Assert.assertEquals(CollUtil.newArrayList(4, 3, 2, 1), sortPageAll);
 	}
-	
+
 	@Test
 	public void containsAnyTest() {
 		ArrayList<Integer> list1 = CollUtil.newArrayList(1, 2, 3, 4, 5);
 		ArrayList<Integer> list2 = CollUtil.newArrayList(5, 3, 1, 9, 11);
-		
+
 		Assert.assertTrue(CollUtil.containsAny(list1, list2));
 	}
 
@@ -560,10 +560,10 @@ public class CollUtilTest {
 	public void containsAllTest() {
 		ArrayList<Integer> list1 = CollUtil.newArrayList(1, 2, 3, 4, 5);
 		ArrayList<Integer> list2 = CollUtil.newArrayList(5, 3, 1);
-		
+
 		Assert.assertTrue(CollUtil.containsAll(list1, list2));
 	}
-	
+
 	@Test
 	public void getLastTest() {
 		// 测试:空数组返回null而不是报错
@@ -571,4 +571,19 @@ public class CollUtilTest {
 		String last = CollUtil.getLast(test);
 		Assert.assertNull(last);
 	}
+
+	@Test
+	public void zipTest() {
+		Collection<String> keys = CollUtil.newArrayList("a", "b", "c", "d");
+		Collection<Integer> values = CollUtil.newArrayList(1, 2, 3, 4);
+		
+		Map<String, Integer> map = CollUtil.zip(keys, values);
+		
+		Assert.assertEquals(4, map.size());
+		
+		Assert.assertEquals(1, map.get("a").intValue());
+		Assert.assertEquals(2, map.get("b").intValue());
+		Assert.assertEquals(3, map.get("c").intValue());
+		Assert.assertEquals(4, map.get("d").intValue());
+	}
 }