user2971387
user2971387

Reputation: 109

Best way to split an arraylist based on a category

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.

Upvotes: 5

Views: 2153

Answers (3)

Tim B
Tim B

Reputation: 41168

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.

Upvotes: 4

Rohit Jain
Rohit Jain

Reputation: 213213

One option is to create a HashMap<String, List<DataType>> by manually iterating over the list. In addition to that, if you can use a 3rd party library, then consider using Guava's Multimaps.index method:

Function<DataType, String> groupFunction = new Function<DataType, String>() {
        @Override
        public String apply(DataType dataType) {
            return dataType.getDType();
        }
};

ImmutableListMultimap<String, DataType> grouped = Multimaps.index(persons, groupFunction);

System.out.println(grouped);

Upvotes: 0

dimoniy
dimoniy

Reputation: 5995

I would create a hash map: HashMap<DataType, List<Data>>. Make sure you override equals() and hashCode() for your DataType class.

Upvotes: 0

Related Questions