日期:2014-05-20 浏览次数:20903 次
package sunflowerbbs.oicp.net; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; public class GroupByKey { private static class Record implements Comparable<Record>, Cloneable { private String _A; private String _B; private String _C; public Record(String _a, String _b, String _c) { _A = _a; _B = _b; _C = _c; } private Record() { } public int compareTo(Record record) { int result = this._A.compareTo(record._A); if (result != 0) { return result; } else { return this._B.compareTo(record._B); } } public Object clone() { Record record = new Record(); record._A = new String(this._A); record._B = new String(this._B); record._C = this._C != null ? new String(this._C) : null; return record; } } public static void main(String[] args) { Record r1, r2, r3, r4, r5, r6, r7; r1 = new Record("A2", "B3", "C3"); r2 = new Record("A3", "B4", "C5"); r3 = new Record("A2", "B3", "C2"); r4 = new Record("A1", "B1", null); r5 = new Record("A2", "B3", "C4"); r6 = new Record("A1", "B2", "C1"); r7 = new Record("A3", "B4", "C7"); ArrayList<Record> list = new ArrayList<Record>(); list.add(r1); list.add(r2); list.add(r3); list.add(r4); list.add(r5); list.add(r6); list.add(r7); Collections.<Record> sort(list); Iterator it = list.iterator(); StringBuffer buffA = new StringBuffer(); StringBuffer buffB = new StringBuffer(); StringBuffer buffC = new StringBuffer(); Record prior = (Record) it.next(); buffA.append(prior._A); buffB.append(prior._B); buffC.append(prior._C == null ? "" : " " + prior._C); //chang it by yourself while (it.hasNext()) { Record next = (Record) it.next(); int result1 = prior._A.compareTo(next._A); int result2 = prior._B.compareTo(next._B); if (result1 != 0) { System.out.println(buffA.toString() + "\n " + buffB.toString() + "\n " + buffC.toString() + "\n "); //chang it by yourself buffA = new StringBuffer(next._A); buffB = new StringBuffer(next._B); buffC = new StringBuffer(next._C); } else if (result2 != 0) { buffB.append("\n " + next._B); buffC.append("\n " + next._C); } else { buffC.append("\n " + next._C == null ? "" : next._C); } prior = (Record) next.clone(); if (!it.hasNext()) { if (!buffA.toString().equals(prior._A)) { System.out.println(prior._A + "\n " + prior._B + "\n " + prior._C + "\n "); //chang it by yourself } else { System.out.println(buffA.toString() + "\n " + buffB.toString() + "\n " + buffC.toString() + "\n "); //chang it by yourself } } } } }