如何用Stream解決兩層List屬性求和問題
更新時間:2023年05月29日 14:21:00 作者:CizelTian
這篇文章主要介紹了如何用Stream解決兩層List屬性求和問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
用Stream解決兩層List屬性求和
假設一個人有很多個銀行賬戶,每個銀行賬戶中存有不同金額的存款,那么我們如何用Stream求一組人的所有存款呢?
首先,我們來建立一下所需的對象。
//賬戶對象
public class Account {
//賬號
private String accountNumber;
//余額
private Integer balance;
public Account() {
}
public Account(String accountNumber, Integer balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public Integer getBalance() {
return balance;
}
public void setBalance(Integer balance) {
this.balance = balance;
}
}//人對象
public class Person {
private String name;
private Integer age;
//賬戶列表
private List<Account> accounts;
public Person() {
}
public Person(String name, Integer age, List<Account> accounts) {
this.name = name;
this.age = age;
this.accounts = accounts;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public List<Account> getAccounts() {
return accounts;
}
public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}
}建立用Stream流計算賬戶總余額的代碼
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class Sum {
public static void main(String[] args) {
//生成包含四個賬戶的賬戶列表
List<Account> accounts1 = new ArrayList<>();
Account account1 = new Account("0001",100);
Account account2 = new Account("0001",200);
Account account3 = new Account("0001",300);
Account account4 = new Account("0001",400);
accounts1.add(account1);
accounts1.add(account2);
accounts1.add(account3);
accounts1.add(account4);
//生成一個名為“zs“的人對象
Person person1 = new Person("zs",20,accounts1);
//生成包含三個賬戶的賬戶列表
List<Account> accounts2 = new ArrayList<>();
Account account5 = new Account("0001",500);
Account account6 = new Account("0001",600);
Account account7 = new Account("0001",700);
accounts2.add(account5);
accounts2.add(account6);
accounts2.add(account7);
//生成一個”ls“的人對象
Person person2 = new Person("ls",30,accounts2);
//生成人列表
List<Person> persons = new ArrayList<>();
persons.add(person1);
persons.add(person2);
//計算總金額
Integer sum = persons.stream().map(Person::getAccounts).flatMap(Collection::stream).map(Account::getBalance).reduce(0,Integer::sum);
System.out.println(sum);
}
}其中flatMap是把兩個List<Account>合并為一個List,方便后續(xù)計算總額
stream計算一個List對象中某個字段總和
int total = list.stream().mapToInt(User::getAge).sum();
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Spring Boot 多環(huán)境配置Maven Profile vs 啟
本文介紹了在Java項目開發(fā)和部署中使用多環(huán)境配置的方法,比較了兩種主要方式:MavenProfile方式和啟動參數方式,結合實例代碼給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧2025-12-12

