Java Collection 建议

标签 java android performance collections

我有一个方法如下

  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/

相关文章:

java - 在websphere本地信任库中添加证书;以编程方式

java - Volatile 与并发收集一起使用?

android - 在ListView.builder中更改特定的ListTile图标

javascript - 在对象数组中的嵌套对象数组中按值查找 - 大型数据集

performance - 用于跟踪过去 X 小时数据的数据结构

java - 区间锁实现

java - 如何更改状态栏字体颜色?

android - 在 Tablelayout 中设置其参数后按钮丢失

Android - MySQL 登录(自动填充)

php - Mysql速度: table with many columns or 2 tables using a join