今天開發的時候遇到個小問題,解決后拿出來曬曬,看看大家還有沒有更好的辦法,呵呵!

要求:兩個字符串數組集合,A數組兩個元素code和name,B數組兩個元素code和number,需要把B數組中沒有A數組的code進行補缺并number置零,并且要按A數組code的排序方式。

舉例:

        List aList = new ArrayList();
aList.add(
new String[]{"1","name1"});
aList.add(
new String[]{"2","name2"});
aList.add(
new String[]{"3","name3"});

List bList1 
= new ArrayList();
bList1.add(
new String[]{"1","5"});
bList1.add(
new String[]{"2","5"});
List bList2 
= new ArrayList();
bList2.add(
new String[]{"3","5"});

解答:

    public List handle(List bList, List aList) {
for (Object object : aList) {
String[] a 
= (String[]) object;
boolean flag = false;
for (Object object1 : bList) {
String[] b 
= (String[]) object1;
if(b[0].equals(a[0])) {
flag 
= true;
break;
}
}
if(!flag) {
String[] b 
= (String[]) bList.get(0);
String[] newA 
= new String[b.length];
newA[
0= a[0];
newA[
1= "0";
bList.add(newA);
}
}
return bList;
}
為了排序還需要加一個排序類

class exComparator implements Comparator {
public int compare(Object arg0, Object arg1) {
String[] vo1 
= (String[])arg0;
String[] vo2 
= (String[])arg1;
int result = 0;
if(Integer.parseInt(vo1[0])<Integer.parseInt(vo2[0])) {
result 
= -1;
else if(Integer.parseInt(vo1[0])>Integer.parseInt(vo2[0])) {
result 
= 1;
else {
result 
= 0;
}
return result;
}
}

驗證:

        List example = handle(bList1,aList);
Collections.sort(example, 
new exComparator());
for (Object object : example) {
String[] ss 
= (String[]) object;
System.out.println(
"========"+ss[0]+"=======" + ss[1]);
}
example 
= handle(bList2,aList);
Collections.sort(example, 
new exComparator());
for (Object object : example) {
String[] ss 
= (String[]) object;
System.out.println(
"========"+ss[0]+"=======" + ss[1]);
}

結果:

========1=======5
========2=======5
========3=======0
========1=======0
========2=======0
========3=======5

 

over............