Here's an approach to filtering out the elements, implemented: using a generic Map (in a generic class) to encapsulate the values.
- The key is the object we want, and the value is determined as follows:
- If the key never existed, we have a list with at most one element, which is the same as the key;
- If the key has existed prior, we have a list with at least one element, which is the same as the key.
Here's how it's laid out. You instantiate it with the type of object you want to split.
public class UniqueSplitter<T> {
public Map<T, List<T>> filterOutElements(final List<?> theCandidateList) {
final Map<T, List<T>> candidateMap = new HashMap<>();
for(Object element : theCandidateList) {
if(candidateMap.containsKey(element)) {
candidateMap.get(element).add((T) element);
} else {
final List<T> elementList = new ArrayList<>();
elementList.add((T) element);
candidateMap.put((T)element, elementList);
}
}
return candidateMap;
}
}