关于java中对list集合中的数据按照某一个属性进行分组

有的时候,我们需要在java中对集合中的数据进行分组运算。

例如:Bill对象有money(float)和type(String)属性,现有个集合List<Bill>,需要按照Bill的type属性进行分组,计算money的总和。有以下两种思路:

思路一:

先计算集合中所有的type情况,然后对于每一种type去遍历集合计算money的和。伪代码如下:

Map<String,String> typeMap = new HashMap<String,String>();

fro (Bill bill : billList) {

typeMap.put(bill.getType,"");

}

fro(String t:typeMap.keySet) {

for (Bill bill : billList) {


if (bill.getType.equals(t)) {

//相应的业务处理

}

}

}

  

思路二:

public class test {  
    public static void main(String[] args) {  
        List<Bill> list = new ArrayList<Bill>();  
        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());  
        }  
    }  
} 

运行结果:

A    2
B    4
C    6

猜你喜欢

转载自www.cnblogs.com/ZJOE80/p/10969418.html