最近的项目需要在一堆数据中按不同字段进行2次分组,小弟比较愚钝,写出了以下代码,总感觉写的不好,高手有更好办法请留言告知,小弟感激不尽! /** */ /** * 该ArrayList是针对ResultSet的转化,包含了一个字符串集合 * @param rs * @return * @throws SQLException */ private ArrayList getResult(ResultSet rs) throws SQLException ... { ArrayList a = new ArrayList(); while (rs.next()) ...{ String[] str = new String[10]; for (int i = 0; i <= 9; i++) ...{ str[i] = rs.getString(i + 1); } a.add(str); } rs.close(); return a == null ? null : getAdvanceResult( a ); } /** */ /** * 追加小计数据 * @param a * @return */ private ArrayList getDetailResult( ArrayList a ) ... { if( a != null ) ...{ for( int i = 0; i < a.size(); i ++ ) ...{ ArrayList x = (ArrayList)a.get(i); double leechdom = 0.0d; double other = 0.0d; for( int k = 0; k < x.size(); k ++ ) ...{ String[] line = (String[])x.get(k); int code = Integer.parseInt( line[4] ); if( code == 1 || code == 2 || code ==3 ) ...{ leechdom += Double.parseDouble( line[6] ); } else ...{ other += Double.parseDouble( line[6] ); } } String[] money = new String[3]; money[0] = String.valueOf( leechdom ); money[1] = String.valueOf( other ); money[2] = String.valueOf( leechdom + other ); x.add(money); } } ArrayList b = a; return b; } /** */ /** * 获取总合计 * @param a * @return */ private ArrayList getTotal( ArrayList a ) ... { ArrayList b = new ArrayList(); double leechdom = 0.0d; double other = 0.0d; for( int i = 0; i < a.size(); i ++ ) ...{ ArrayList c = (ArrayList)a.get(i); String[] s = ( String[] )c.get(c.size() - 1); leechdom += Double.parseDouble( s[0] ); other += Double.parseDouble( s[1] ); } String[] money = new String[3]; money[0] = String.valueOf( leechdom ); money[1] = String.valueOf( other ); money[2] = String.valueOf( leechdom + other ); b.add(money); return b; } /** */ /** * 该ArrayList包含特定数量个ArrayList,表示各个收款员的统计数据 * @param a * @return */ private ArrayList getAdvanceResult( ArrayList a ) ... { ArrayList b = new ArrayList(); if( a != null ) ...{ ArrayList c = new ArrayList(); for( int i = 0; i < a.size() - 1; i ++ ) ...{ String[] s1 = (String[])a.get(i); String[] s2 = (String[])a.get(i+1); if( s1[0].trim().equals(s2[0].trim()) ) // 同一个人 ...{ if( ( i>0 && !s1[0].trim().equals( ((String[])a.get(i-1))[0].trim() ) ) || i == 0 ) ...{ c.add(s1); } c.add(s2); if( i == a.size() - 2 ) ...{ b.add(c.clone()); } } else ...{ b.add(c.clone()); c = new ArrayList(); if( i>0 && !s1[0].trim().equals( ((String[])a.get(i-1))[0].trim() ) ) ...{ c.add(s1); } if( i == a.size() - 2 ) ...{ c.add(s2); b.add(c.clone()); } } } } return getDetailResult(b); }