我有两个ArrayList
类String
类型,想要按如下方式混合:
SPK = [A,A,A,B,A,A,A,A,A,B]
和
DA= [ofm,sd,sd,sd,sd,sd,sd,sd,sd,sv]
我需要在其他String
中创建一些ArrayList
,如下所示:
SPK_DA = [ofmAsdAsdAB, sdBA, sdAsdAsdAsdAsdAB]
在这个集合中,我需要在SPK数组中转换(从A到B)之前等同先前的类似元素。
我写了一个程序,但它增加了一个额外的sdA(我不知道为什么我不能做这么简单的事情)。
for (int i=0; i <SPK.size()-1; i++){
if (SPK.get(i)==SPK.get(i+1) && (i+1)<= SPK.size()){
speakerChain = DA.get(i)+SPK.get(i);
speakerChain1=DA.get(i+1)+SPK.get(i+1);
SPKTrace.add(speakerChain);
SPKTrace.add(speakerChain1);
}else if (SPK.get(i)!=SPK.get(i+1)){
if (SPKTrace.size()!=0){
SPKTrace.add(SPK.get(i+1));
//SPKString = removeDuplicates (SPKTrace);
String S1 = arrayTostring(SPKTrace);
SPKResource.add(S1);
SPKTrace.clear();
}else {
SPKTrace.add(DA.get(i)+SPK.get(i)+SPK.get(i+1));
//SPKString = removeDuplicates (SPKTrace);
String S1 = arrayTostring(SPKTrace);
SPKResource.add(S1);
SPKTrace.clear();
}
}
}
}
}
System.out.println(SPKResource.toString());
My Output: [ofmAsdAsdAsdAB, sdBA, sdAsdAsdAsdAsdAsdAsdAsdAB]
当我使用for循环时,它会创建更多的sdA ....
答案 0 :(得分:0)
Indicies.add(0);
for (int i = 0; i < SPK.size() - 1; i++) {
if (SPK.get(i) != SPK.get(i + 1)) {
Indicies.add(i + 1);
}
}
for (int i = 0; i < Indicies.size() - 1; i++) {
Count.add(Indicies.get(i + 1) - Indicies.get(i));
}
Count.add((SPK.size() - Indicies.get(Indicies.size() - 1)));
System.out.println("count:" + Count);
int counter = 0;
int newIndex =0;
for (int j = 1; j <= Count.size(); j++) {
String element = "";
for (int kk = 0; kk < (Count.get(j-1)); kk++) {
element = element + (DA.get(kk+newIndex) + SPK.get(kk+newIndex));
}
newIndex = newIndex+Count.get(j-1);
if (element.endsWith("A")){
SPKResource.add(element+"B");
} else if (element.endsWith("B")){
SPKResource.add(element+"A");
}
}
}
}
for (String S:SPKResource){
System.out.println(SPKResource);
}
上面的代码可以给我答案,但我认为这是非常低效的。有什么想法让它更有效率吗?