-4

I have an ArrayList:

ArrayList<Integer> example = new ArrayList<Integer>();
example.add(1);
example.add(1);
example.add(2);
example.add(3);
example.add(3);

So I want to make others three ArrayLists containing in which one the same values (where there is just one value the ArrayList would have just the one).

Is that possible?

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
user2600853
  • 101
  • 1
  • 12
  • 5
    Three passes over and it still confuses me. Do you want a list that only has one element, or three lists that contain one distinct element each? – Makoto Jul 24 '13 at 04:58
  • 2
    possible duplicate of [How to clone ArrayList and also clone its contents?](http://stackoverflow.com/questions/715650/how-to-clone-arraylist-and-also-clone-its-contents) – Nir Alfasi Jul 24 '13 at 04:58
  • 1
    I want to group the same elements creating new ArrayLists. If I have (1,1,2) I want to create an ArrayList containing 1, 1 and other containing 2. – user2600853 Jul 24 '13 at 05:04
  • One thing you could do is have a `Map>`, and have each `Integer` map to its corresponding `ArrayList`. – Dennis Meng Jul 24 '13 at 05:09

1 Answers1

0

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;
    }
}
Makoto
  • 104,088
  • 27
  • 192
  • 230