10000 Added TypedCollectionsUtilities class. · randomcoding/JavaUtilities@1e4794b · GitHub
[go: up one dir, main page]

Skip to content

Commit 1e4794b

Browse files
author
Tym the Enchanter
committed
Added TypedCollectionsUtilities class.
This provides a means of getting collections of one type from collections of another. E.g. getting all the elements that are instances of java.lang.Double from a collection of java.lang.Number
1 parent 093558a commit 1e4794b

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
* (c) Tym The Enchanter (tymtheenchanter@randomcoding.co.uk), 5 Jun 2010
3+
*/
4+
package uk.co.randomcoding.java.util.collection;
5+
6+
import java.util.Collection;
7+
import java.util.HashSet;
8+
9+
/**
10+
* <p>
11+
* Class to provide operations for typed collections.
12+
* </p>
13+
* Created on: 5 Jun 2010<br>
14+
*
15+
* @author Tym the Enchanter <tymtheenchanter@randomcoding.co.uk>
16+
*/
17+
public class TypedCollectionUtilities
18+
{
19+
/**
20+
* Creates a new collection of the elements in the source collection that are also of the target collection type
21+
* <p>
22+
* Added by: Tym the Enchanter <tymtheenchanter@randomcoding.co.uk><br>
23+
* On: 5 Jun 2010<br>
24+
* </p>
25+
*
26+
* @param <T> The type of the returned collection
27+
* @param sourceCollection The source collection to get the elements from
28+
* @param targetCollectionType The type of the returned collection
29+
* @return A collection of the specified type, containing those elements from the source collection that are of the
30+
* required type
31+
*/
32+
@SuppressWarnings("unchecked")
33+
public static <T> Collection<T> extractTypedCollection(Collection<?> sourceCollection, Class<T> targetCollectionType)
34+
{
35+
Collection<T> typedCollection = new HashSet<T>();
36+
37+
for (Object sourceObject : sourceCollection)
38+
{
39+
if (targetCollectionType.isAssignableFrom(sourceObject.getClass()))
40+
{
41+
typedCollection.add((T) sourceObject);
42+
}
43+
}
44+
45+
return typedCollection;
46+
}
47+
}

0 commit comments

Comments
 (0)
0