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

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

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

思路一:code

先计算集合中全部的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)) {

//相应的业务处理

}

}

}

  

思路二:blog

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

运行结果:get

A    2
B    4
C    6class

相关文章
相关标签/搜索