日期:2014-05-20 浏览次数:20998 次
import java.util.*;
public class GroupTest {
    public static void main(String[] args) throws Throwable {
        List<String[]> list = new ArrayList<String[]>();
        list.add(new String[] {"53", "设备登记管理", "16", "/dev/a", null, "0", "2"});
        list.add(new String[] {"53", "设备登记管理", "16", "/dev/a", null, "1", "2"});
        list.add(new String[] {"53", "设备登记管理", "16", "/dev/a", null, "2", "2"});
        list.add(new String[] {"54", "设备登记管理", "16", "/dev/b", null, "0", "2"});
        list.add(new String[] {"54", "设备登记管理", "16", "/dev/b", null, "4", "2"});
        list.add(new String[] {"55", "设备登记管理", "16", "/dev/c", null, "3", "2"});
        list.add(new String[] {"55", "设备登记管理", "16", "/dev/c", null, "4", "2"});
        list.add(new String[] {"80", "ffff", "16", null, null, "0", "1"});
        List<String[]> result = group(list, new int[]{0, 1, 2, 3, 4, 6}, new int[] {5});
        for (String[] record : result) {
            System.out.println(Arrays.toString(record));
        }
    }
    
    @SuppressWarnings("unchecked")
    public static <T extends Comparable<T>> List<T[]> group(List<T[]> list, int[] groupId, int[] unionId) {
        List<T[]> result = new ArrayList<T[]>();
        for (T[] record : list) {
            boolean found = false;
            for (T[] union : result) {
                boolean same = true;
                for (int id : groupId) {
                    same = same && (union[id] == record[id] || 
                                   (union[id] != null && record[id] != null && 
                                    union[id].compareTo(record[id]) == 0));
                }
                if (same) {
                    for (int id : unionId) {
                        if (union[id] instanceof String) {
                            union[id] += "," + record[id];
                        } else {
                            //other union operation
                        }
                    }
                    found = true;
                    break;
                }
            }
            if(!found) {
                result.add(Arrays.copyOf(record, record.length));
            }
        }
        return result;
    }
}