今天开发的时候遇到个小问题,解决后拿出来晒晒,看看大家还有没有更好的办法,呵呵!

要求:两个字符串数组集合,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............