package com.uniclick.dap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class TestDoubleArray { /** * @function 此类的功能是把二维字符串数组的前2列相同的合并,后2列相应的值相加 * @author [email protected] * @time 2013-02-24 * @param args */ public static void main(String[] args) { String[][] arr = { {"新浪","学生","10","5"}, {"网易","学生","9","4"}, {"新浪","白领","8","3"}, {"新浪","学生","15","2"}, {"网易","白领","19","7"}, {"百度","白领","20","5"}, {"新浪","学生","4","1"}, {"新浪","白领","1","1"}, {"网易","学生","9","4"}, {"网易","学生","9","4"}, {"网易","学生","5","5"}, }; //add to set Set<String> set = new HashSet<String>(); for(int i=0;i<arr.length;i++){ set.add(arr[i][0]+"\t"+arr[i][1]); } //此二维数组用来装结果 String[][] result = new String[set.size()][4]; // Object[][] result = new Object[set.size()][4]; // Iterator<String> itr = set.iterator(); int r = 0; while(itr.hasNext()){ String mark = itr.next(); //如果没有初始化,就赋值为0,免得null报错 int res2 = Integer.valueOf(result[r][2]==null?"0":result[r][2]); int res3 = Integer.valueOf(result[r][3]==null?"0":result[r][3]); for(int i=0;i<arr.length;i++){ if(mark.equalsIgnoreCase(arr[i][0]+"\t"+arr[i][1])){ result[r][0]=arr[i][0]; result[r][1]=arr[i][1]; res2 += Integer.valueOf(arr[i][2]); res3 += Integer.valueOf(arr[i][3]); } result[r][2]=Integer.toString(res2); result[r][3]=Integer.toString(res3); } r++; } //print result array for(int i=0;i<result.length;i++){ System.out.println(result[i][0]+":"+result[i][1]+":"+result[i][2]+":"+result[i][3]); } } }
console print:
新浪:白领:9:4
新浪:学生:29:8
百度:白领:20:5
网易:白领:19:7
网易:学生:32:17
PS:这个问题困扰了我几天了,绞尽脑汁才把这功能实现,不知还有没有更好的方法实现。工期紧,留待以后再优化。