Best way to split an arraylist based on a category

arraylist, java

Solution

The way I'd do this is to create a Map:

Map<String, List<DataType>> data;

Then loop through your original array, for each value insert them into the Map using dType as the key.

for (DataType dt: toSort) {
    List<DataType> list = data.get(dt.dType);
    if (list == null) {
        list = new ArrayList<>();
        data.put(dt.dType, list);
    }
    list.add(dt);
}

Now you have them all sorted nicely.

Problem

I have an ArrayList, where DataType is a class: ``` class DataType { String id; String dType; String description; // setters and getters follow } ``` With the given `ArrayList<Datatype>`, I want to create sub lists, such that every sublist has the same value for `dType`. i.e all `DataType` Objects having same value for `dType` should come in one sublist and so on. Further, all sublists will be added to an `ArrayList<ArrayList<Datatype>>` as created. Could someone please suggest the most appropriate approach for this.

Original source