【问题标题】:Group by functionality in Java在 Java 中按功能分组
【发布时间】:2014-12-10 16:48:58
【问题描述】:

我正在尝试编写一个 Java 程序来加载数据(从制表符分隔的 DAT 文件)并确定按国家和信用等级分组的欧元 (EUR) 平均金额。

我有 2 个问题,

  1. 将数据拆分为数组后加载到数据结构中的最佳方法是什么?
  2. 如何在 Java 中提供分组功能

更新:我已经进行了第一次尝试,这就是实现的样子。感觉还有改进的余地。

    /**
 * @param rows - Each row as a bean
 * This method will group objects together based on Country/City and Credit Rating
 */
static void groupObjectsTogether(List<CompanyData> rows) {
    Map<String, List<CompanyData>> map = new HashMap<String, List<CompanyData>>();

    for(CompanyData companyData : rows){
        String key;

        if(companyData.getCountry().trim().equalsIgnoreCase("") || companyData.getCountry() == null){
            key = companyData.getCity()+":"+companyData.getCreditRating();          //use city+creditRating as key
        }else{
            key = companyData.getCountry()+":"+companyData.getCreditRating();       //use country+creditRating as key
        }

        if(map.get(key) == null){
            map.put(key, new ArrayList<CompanyData>());
        }
        map.get(key).add(companyData);
    }

    processGroupedRowsAndPrint(map);
}

【问题讨论】:

  • 您可以使用数据库(如 HSQL)还是必须全部是 Java?
  • 你的数据结构是什么样的?你有包含单元格的一维数组还是包含行和单元格的二维数组?
  • 我不能使用数据库,需要让我遵循最佳编码实践。例如。我需要使用 BigDecimal 来实现货币精度。

标签: java string collections


【解决方案1】:

这完全取决于机器的数据量和性能(CPU 与内存)。如果数据量不大(少于数百万条记录或列)并且列数是固定的,那么您可以使用

简单地将所有数据放入数组中
String[] row = String.split(";");

使用 ; 分割每一行作为分隔符。然后您可以使用 HashMap 实现分组功能,即:

ArrayList<String[]> rowAr = new ArrayList<String[]>();
HashMap<String,ArrayList<Integer>> map = new HashMap<String,ArrayList<Integer>>();
int index = 0;
for (String rowStr: rows) {
    String[] row = rowStr.split(";");
    rowAr.add(row);
    String companyCode = row[0];
    //please keep in mind that for simplicity of the example I avoided
    //creation of new array if it does not exist in HashMap
    ((ArrayList<Integer>)map.get(companyCode)).add(index);
    index++;
}

对于上述任何语法或其他简单错误,我深表歉意(我手头没有任何工具来验证是否有任何愚蠢的错误)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 2013-09-19
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 2016-03-14
    相关资源
    最近更新 更多