Skip to content

Commit a9b3cd9

Browse files
committed
提取重构
1 parent 19b1865 commit a9b3cd9

File tree

2 files changed

+23
-10
lines changed

2 files changed

+23
-10
lines changed

src/main/java/com/bestvike/linq/enumerable/ToCollection.java

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import com.bestvike.linq.IEnumerable;
77
import com.bestvike.linq.exception.Errors;
88

9-
import java.util.ArrayList;
109
import java.util.HashMap;
1110
import java.util.HashSet;
1211
import java.util.List;
@@ -55,15 +54,7 @@ public static <TSource> List<TSource> toList(IEnumerable<TSource> source) {
5554
return listProvider._toList();
5655
}
5756

58-
if (source instanceof ICollection) {
59-
ICollection<TSource> collection = (ICollection<TSource>) source;
60-
return collection._toList();
61-
}
62-
63-
List<TSource> list = new ArrayList<>();
64-
for (TSource item : source)
65-
list.add(item);
66-
return list;
57+
return EnumerableHelpers.toList(source);
6758
}
6859

6960
public static <TSource, TKey> Map<TKey, TSource> toMap(IEnumerable<TSource> source, Func1<TSource, TKey> keySelector) {

src/main/java/com/bestvike/linq/enumerable/__EnumerableHelpers.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,12 @@
44
import com.bestvike.linq.IEnumerable;
55
import com.bestvike.linq.IEnumerator;
66
import com.bestvike.linq.util.ArrayUtils;
7+
import com.bestvike.linq.util.ListUtils;
78
import com.bestvike.out;
89

10+
import java.util.ArrayList;
11+
import java.util.List;
12+
913
/**
1014
* Created by 许崇雷 on 2018-05-07.
1115
*/
@@ -150,4 +154,22 @@ public static <T> Object[] toArray(IEnumerable<T> source, out<Integer> length) {
150154
length.value = 0;
151155
return ArrayUtils.empty();
152156
}
157+
158+
//Converts an enumerable to an list.
159+
public static <T> List<T> toList(IEnumerable<T> source) {
160+
assert source != null;
161+
162+
if (source instanceof ICollection) {
163+
ICollection<T> collection = (ICollection<T>) source;
164+
int count = collection._getCount();
165+
return count == 0 ? ListUtils.empty() : collection._toList();
166+
}
167+
168+
List<T> list = new ArrayList<>();
169+
try (IEnumerator<T> e = source.enumerator()) {
170+
while (e.moveNext())
171+
list.add(e.current());
172+
}
173+
return list;
174+
}
153175
}

0 commit comments

Comments
 (0)