Java集合中如何解决数据分类汇总的问题(需要高手解决)
我从数据库中查询出来的数据是一个集合,要对数据进行分类汇总
xm kc math chinese
--------------------
张三 语文 65 95
李四 数学 75 80
李四 语文 80 40
李四 语文 80 40
最后要显示的效果是
xm kc 一学期 二学期
--------------------
张三 语文 65 95
语文 65 95
张三 65 95
李四 数学 75 80
数学 75 80
李四 语文 80 40
李四 语文 80 40
语文 160 80
李四 235 160
总计 295 255
//////////////////////////////////////////////////////////
我自己大概写了个方法出来,还没完全实现
希望大家帮帮我,看看是否能用递归实现呀
Test.java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List li=new ArrayList();
//第一个学生
Student ww=new Student();
ww.setName("ww");
ww.setChinese(95);
ww.setMath(65);
//第二个学生
Student zx=new Student();
zx.setName("zx");
zx.setChinese(80);
zx.setMath(75);
//第三个学生
Student zxa=new Student();
zxa.setName("zx");
zxa.setChinese(40);
zxa.setMath(80);
//第四个学生
Student yy=new Student();
yy.setName("yy");
yy.setChinese(40);
yy.setMath(80);
li.add(ww);
li.add(zx);
li.add(zxa);
li.add(yy);
int m = 0;
int c = 0;
String str="";
List list = new ArrayList();
for(int i=0;i<li.size();i++)
{
Student real=(Student)li.get(i);
if(i==0)
{
m=real.getMath();
c=real.getChinese();
str=real.getName();
list.add(real);
}
else if(real.getName().equals(str)) //是否可以是动态的,不固定某个属性
{
m+=real.getMath();
c+=real.getChinese();
list.add(real);
}
else
{
Student Nstb=new Student();
Nstb.setName(str);
Nstb.setMath(m);
Nstb.setChinese(c);
list.add(Nstb);
str=real.getName();
c=real.getChinese();
m=real.getMath();
list.add(real);
}
if(li.size()-1==i)
{
Student Nstb=new Student();
Nstb.setName(str);
Nstb.setMath(m);
Nstb.setChinese(c);
list.add(Nstb);
}
}
Iterator endlist=list.iterator();
while(endlist.hasNext())
{
Student st=(Student)endlist.next();
System.out.println(st.getName()+":"+st.getMath()+":"+st.getChinese());
}
}
}
//Student.java
public class Student {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
private String name;
private String hometown;
private int chinese;
private int math;
public String getHometown() {
return hometown;
}
public void setHometown(String hometown) {
this.hometown = hometown;
}
public int getChinese() {
return chinese;
}
public void setChinese(int chinese) {
this.chinese = chinese;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}