在java中的向量/数组中对值进行分组和添加

时间:2013-08-30 04:53:23

标签: java arrays sorting vector text-parsing

我是Java的新手,必须对其他人提供给我的分隔符分隔数据进行一些操作,我已经从中获取了所需的字段并存储到字符串数组中。它看起来有点类似于以下内容:

     String [] toseparate =null;
     Vector <String> myVector = new Vector<String>();
     myVector.add (a xyz 12 b efg 13 a pqr 45 c erer 18 a vbv 27 d tag 40 c etc 16....)
    //These values are derived from a separate array which I've parsed based on delimiters.
     toseparate = myVector.toArray(new String[myVector.size()]);

(依此类推),这是一个长度在50个索引范围内且未排序的数组。         结果应该是:

    a,84,b,13,c,34....

(即与字符串对应的数字的总和)。除此之外,a,b,c ...的顺序无关紧要。 我认为它也可以使用多维数组(2D)完成,并将根据专家意见改变方法。
请帮帮我吧 非常感谢你。

2 个答案:

答案 0 :(得分:0)

为什么不使用split()函数来解析分隔的字符串?看一眼: http://pages.cs.wisc.edu/~hasti/cs302/examples/Parsing/parseString.html

无论你如何解析,看起来你的所有数据都是三元组,其中只有第一个和最后一个值很重要:

a xyz 12 b efg 13 a pqr 45 c erer 18 a vbv 27 d tag 40 c etc...

解析为:

a 12 b 13 a 45 c 18 a 27 d 40 ...

假设你可以在三个数组中循环遍历数组并随时累积值。在伪代码中:

for( i = 0; i < array.length(); i+=3) {
    if(!map.containsKey( array[i] )) map.put( array[i], array[i+2] );
    else map.put( array[i], map.get( array[i] ) + array[i+2] );
}

对于地图,我想可以使用Hashmap&lt; String,int&gt ;.

答案 1 :(得分:0)

Map<String, Integer> totals = new HashMap<String, Integer>();
for(int i = 0 ; i < myVector.size(); i += 3) {
    Integer total = totals.get(myVector.get(i));
    if(total == null) {
        total = 0;
    }
    total += Integer.parseInt(myVector.get(i + 2));
    totals.put(myVector.get(i), total);
}