Java集合中如何解决数据分类汇总的问题(需要高手解决)

cengxiong 2006-04-29 10:55:39
我从数据库中查询出来的数据是一个集合,要对数据进行分类汇总

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;
}

}


...全文
397 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
cengxiong 2006-04-29
  • 打赏
  • 举报
回复
下面就是我要显示的结果拉!!对Xm 和ck进行了汇总亚
zuoyangguang 2006-04-29
  • 打赏
  • 举报
回复
看不出你要的结果是什么

67,549

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧