[quote]
我是用的SSH框架
List list = billFacade.findBillByUserId(userInfo);
我是想把查询出来的list内容分组一下
我想用bill对象中的 type 属性来分组 然后把 money 属性的值全部加起来
意思就是说,把所有只要type一样的, 就把他们的money加起来。
[/quote]
希望大哥大姐帮帮我。 :cry:
[code="java"]
List list = billFacade.findBillByUserId(userInfo);
Map group = new HashMap();
String type = null;
Float moneyTotal = 0f;
for(Bill bill : list){
type = bill.getType();
moneyTotal = group.get(type);
if(moneyTotal == null){
moneyTotal = 0f;
}
group.put(type, moneyTotal + bill.getMoney());
}
[/code]
是需要得到一个新的Bill-List 里面相同type数据合并 统计相同type的money结果?
很垃圾的一段代码
[code="java"]
package com.zhangxuan.platform.test;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
public class T {
public static void main(String[] args) {
List lb = new ArrayList();
Bill b;
for(int i = 0; i < 20; i ++) {
b = new Bill();
if(i % 2 == 0)
b.setType("t1");
else
b.setType("t2");
b.setMoney(i + 1000);
lb.add(b);
}
TreeSet tss = new TreeSet();
for(Bill bi : lb) {
tss.add(bi.getType());
}
List lbs = new ArrayList();
int total = 0;
for(String t : tss) {
b = new Bill();
b.setType(t);
for(Bill bl : lb) {
if(t.equals(bl.getType())) {
total += bl.getMoney();
}
}
b.setMoney(total);
lbs.add(b);
}
for(Bill bill : lbs ) {
System.out.println(bill.getType() + " - " + bill.getMoney());
}
}
}
class Bill {
String type;
int money;
public Bill() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
[/code]
[code="java"]public class test {
public static void main(String[] args) {
List list = new ArrayList();
Bill b = new Bill();
b.setType("A");
b.setMoney(1);
list.add(b);
b = new Bill();
b.setType("B");
b.setMoney(2);
list.add(b);
b = new Bill();
b.setType("C");
b.setMoney(3);
list.add(b);
b = new Bill();
b.setType("A");
b.setMoney(1);
list.add(b);
b = new Bill();
b.setType("B");
b.setMoney(2);
list.add(b);
b = new Bill();
b.setType("C");
b.setMoney(3);
list.add(b);
List<Bill> bi = new ArrayList<Bill>();
for (Bill bill : list) {
boolean state = false;
for (Bill bills : bi) {
if(bills.getType().equals(bill.getType())){
int money = bills.getMoney();
money += bill.getMoney();
bills.setMoney(money);
state = true;
}
}
if(!state){
bi.add(bill);
}
}
for (Bill bill : bi) {
System.out.println(bill.getType() +" " +bill.getMoney());
}
}
}[/code]
那啥 和LS应该差不多..
Collections排序,Map分组,计算。
蛋疼的问题
你这个问题,结果可以直接从数据库中查询出来,不需要java代码做处理