Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to split an arraylist based on a category

Tags:

java

arraylist

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.

like image 977
user2971387 Avatar asked Oct 02 '22 03:10

user2971387


1 Answers

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.

like image 70
Tim B Avatar answered Oct 13 '22 11:10

Tim B