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

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

2
史帝夫
iT邦新手 3 級 ‧ 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邦新手 3 級 ‧ 2021-09-17 15:58:28

有可能是下面

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

我要發表回答

立即登入回答