我有一个方法如下
public List<List<CustomClass>> categorize(List<CustomClass> customClass){
List<List<CustomClass>> returnValue = new ArrayList<>();
for (CustomClass customClassValue: customClass) {
List<CustomClass> one = new ArrayList<>(), two = new ArrayList<>(), three = new ArrayList<>(), four = new ArrayList<>();
switch (customClassValue.getAge()){
case 1:
one.add(customClassValue);
break;
case 2:
two.add(customClassValue);
break;
case 3:
three.add(customClassValue);
break;
case 4:
four.add(customClassValue);
break;
}
returnValue.add(one);
returnValue.add(two);
returnValue.add(three);
returnValue.add(four);
}
return returnValue;
}
除了使用List<List<CustomClass>>
之外,java集合中还有其他选择吗?从有效性和绩效的角度来看。
简单地描述该函数的作用:
接受自定义对象列表的输入,并根据对象中的字段对它们进行分类,并分别返回每个类别项。
最佳答案
当你想将东西分类到桶中时,我的第一 react 是使用 Map
而不是List
。划分List<CustomClass>
根据年龄进入子列表似乎是使用 Map<Integer, List<CustomClass>>
的最佳时机。这是一种方法:
public Map<Integer, List<CustomClass>> categorize(List<CustomClass> customClass) {
Map<Integer, List<CustomClass>> returnValue = new HashMap<>();
for (CustomClass customClassValue: customClass) {
List<CustomClass> sublist = returnValue.get(customClassValue.getAge());
if (sublist == null) {
sublist = new ArrayList<>();
returnValue.put(customClassValue.getAge(), sublist);
}
sublist.add(customClassValue);
}
return returnValue;
}
关于Java Collection 建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45204821/