iT邦幫忙

0

如何在java 中 處理 sum() group by ?

sql: select name , sum(amount) from table group by name
想問以上sql 怎樣在JAVA 中寫呢

public class Obj{
    String Name;
    int amount;
}

public List<Obj> getTotal (List<Obj> objList){
    List<Obj> resultList= new LinkedList<Obj>();
    for ( Obj a :objList ){
           //code//
    }
    
    return resultList;
}

data:
Name Amount
apple 100
orange 100
apple 100
banana 100

2 個回答

2
史帝夫
iT邦新手 5 級 ‧ 2021-09-17 15:57:46
Map<String, Integer> result = objList.stream().collect(Collectors.groupingBy(Obj::getName, Collectors.summingInt(Obj::getAmount)));
System.out.println("result = " + result);//result = {banana=100, orange=100, apple=200}
1
chichi
iT邦新手 4 級 ‧ 2021-09-17 15:58:28

有可能是下面

resultList.stream().collect(
                Collectors.groupingBy(Obj::getName, Collectors.summingInt(Obj::getAmount)));

我要發表回答

立即登入回答