在java中,在向量/数组中分组并添加值
我是Java新手,必须对其他人提供给我的分隔符分隔的数据进行一些操作,我已经从中获取了所需的字段并存储到字符串数组中。它看起来有点类似于以下内容:在java中,在向量/数组中分组并添加值,java,arrays,sorting,vector,text-parsing,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 e
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()]);
除此之外,a,b,c的顺序。。。没关系。
我认为也可以使用多维数组(2D)来完成,并将根据专家建议改变方法请帮我解决这个问题。
非常感谢。为什么不使用split()函数来解析分隔字符串?看看: 无论您如何解析,看起来所有数据都是三元组,其中只有第一个和最后一个值重要:
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] );
}
(i=0;i{
if(!map.containsKey(数组[i])map.put(数组[i],数组[i+2]);
else-map.put(数组[i],map.get(数组[i])+数组[i+2]);
}
对于map,我想您可以使用Hashmap。map totals=newhashmap();
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);
}
对于(int i=0;i <>代码>你有什么特别的困难吗?请展示你已经尝试过的东西。我无法弄清楚使用什么方法和获得这些值。考虑使用<代码> HashMap < /代码>。开始查看地图(HasMead等)。具体来说,我会考虑使用HasMAPI已经从一个很长的字符串中分离出这些值之后,数据实际上是5组(并且可以根据新的需求而变化),为了简单起见,我已经显示了三重态。我已经在使用loop了,但是如果是java的话,我正在寻找更有效的方法。在5个值和每一组5之间是否有不同的分隔符?如果是这样的话,可能有一种更有效的方法。我从一个使用split(regex)分隔符的字符串中得到了这些值,如果有一种有效的方法,可以这样做吗?如果有两个不同的分隔符,可以拆分所有组,然后在循环组时拆分这些值。如果这样做,您可以同时使用hashmap添加值。
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);
}