简体   繁体   English

基于类别拆分arraylist的最佳方法

[英]Best way to split an arraylist based on a category

I have an ArrayList, where DataType is a class: 我有一个ArrayList,其中DataType是一个类:

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 . 使用给定的ArrayList<Datatype> ,我想创建子列表,以便每个子列表具有相同的dType值。 ie all DataType Objects having same value for dType should come in one sublist and so on. 即,具有相同dType值的所有DataType对象应该位于一个子列表中,依此类推。

Further, all sublists will be added to an ArrayList<ArrayList<Datatype>> as created. 此外,所有子列表都将添加到创建的ArrayList<ArrayList<Datatype>>中。

Could someone please suggest the most appropriate approach for this. 有人可以为此建议最合适的方法。

The way I'd do this is to create a Map: 我这样做的方法是创建一个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. 然后循环遍历原始数组,对于每个值,使用dType作为键将它们插入到Map中。

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. 现在你把它们全部整理好了。

I would create a hash map: HashMap<DataType, List<Data>> . 我会创建一个哈希映射: HashMap<DataType, List<Data>> Make sure you override equals() and hashCode() for your DataType class. 确保为DataType类重写equals()hashCode()

One option is to create a HashMap<String, List<DataType>> by manually iterating over the list. 一种选择是通过手动迭代HashMap<String, List<DataType>>来创建HashMap<String, List<DataType>> In addition to that, if you can use a 3rd party library, then consider using Guava's Multimaps.index method: 除此之外,如果您可以使用第三方库,那么请考虑使用Guava的Multimaps.index方法:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM