将带有计数的awk 2D数组转换为java中的hashmap

时间:2012-07-26 17:19:58

标签: java awk hashmap

我发现这个问题很有趣。我正在使用一个具有键,值,计数相同的awk 2D数组。那是打印到文件。此文件采用以下格式

A100|B100|3
A100|C100|2
A100|B100|5

现在我有一个这样的文件..我的动机是将此文件转换为哈希映射,以便哈希映射的最终输出为。

A100|B100|8
A100|C100|2

只是汇总

挑战在于,这个有3个维度,而不是2个维度。我确实有一个以下格式的另一个文件

D100|4
H100|5
D100|6

我很容易聚合上面的内容,因为它只是2D而我使用下面的代码来做那个

String[] fields= strLine.trim().split("\\|");
if(hashmap.containsKey(fields[0]))
{
//Update the value of the key here
hashmap.put(fields[0],hashmap.get(fields[0]) + Integer.parseInt(fields[1]));
}
else
{
//Inserting the key to the map
hashmap.put(fields[0],Integer.parseInt(fields[1]));
}

所以这很容易实现。

但是当涉及到3D时,我必须在里面进行另一次检查。我的想法是维持一个[B100,5(beanObject [5])]

  Map<String,beanClassObject> hashmap=new Map<String,beanClassObject>();

secongField哈希映射,它已在代码中使用,该代码在创建的ben对象下标和键之间具有映射关系,作为第二个字段“例如它是”

此bean类将具有文件的第2和第3个字段的getter和setter方法。我希望我明白这一点。所以这个的实现将是

if(hashmap.containsKey(fields[0]))
{
   **//Have to check whether the the particular key value pair already exists ... I dint find any method for this ... Just a normal iteration is there .. Could you ppl guide me regarding this**

    //Update the value of the key here
     secondFieldHashMap.get(fields[1]).COunt= secondFieldHashMap.get(fields[1]).getCOunt+ Integer.parseInt(fields[2]));
   }
   else
    {
     //Inserting the key to the map
     hashmap.put(fields[0],Integer.parseInt(fields[1]));
     secondFieldHashMap.get(fields[1]).COunt=  Integer.parseInt(fields[2]));
    }
else
{

 // This meands there is no key field
 // Hence insert the key field and also update the count of seconfFieldHashMap as done previously.
 }

请告诉你,请提出一些有关此事的想法。谢谢

1 个答案:

答案 0 :(得分:0)

考虑使用Google Guava库中提供的Table

相关问题