Java Stream MapReduce大資料開發模型
阿新 • • 發佈:2020-12-10
技術標籤:java基礎知識--第一行程式碼streamjava
實現一個購買商品後,對資料進行處理統計的功能.
將購買的商品資訊儲存在Orders類中
public class Orders {
private String name;
private double price;
private int amount;
public Orders(String name, double price, int amount) {
this.name = name;
this.price = price;
this .amount = amount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
通過map()處理資料,輸出購買每一件商品的總價
public static void main(String[] args) {
List<Orders> list = new ArrayList<>();
list.add(new Orders("dq csdn", 60.00, 80));
list.add(new Orders("dq android", 100.20, 73));
list.add(new Orders("dq java", 72.02, 15));
//計算購買每一件商品的總價
list.stream().map((x) -> x.getAmount() * x.getPrice()).forEach(System.out::println);
}
通過reduce()對map()處理後的資料進行統計
double all = list.stream().map((x) -> x.getAmount() * x.getPrice()).reduce((x, y) -> x + y).get();
System.out.println(String.format("%.2f", all));
使用DoubleStream介面中DoubleSummaryStatistics類進行資料統計
DoubleSummaryStatistics statistics=list.stream().mapToDouble((x)->x.getAmount()* x.getPrice()).summaryStatistics();
System.out.println("商品品種"+statistics.getCount()+"商品總花費"+statistics.getSum()+"商品平均花費"+statistics.getAverage()+"最高花費"+statistics.getMax()+"最低花費"+statistics.getMin());
總程式碼:
import java.util.ArrayList;
import java.util.DoubleSummaryStatistics;
import java.util.List;
public class Orders {
private String name;
private double price;
private int amount;
public Orders(String name, double price, int amount) {
this.name = name;
this.price = price;
this.amount = amount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public static void main(String[] args) {
List<Orders> list = new ArrayList<>();
list.add(new Orders("dq csdn", 60.00, 80));
list.add(new Orders("dq android", 100.20, 73));
list.add(new Orders("dq java", 72.02, 15));
DoubleSummaryStatistics statistics=list.stream().mapToDouble((x)->x.getAmount()* x.getPrice()).summaryStatistics();
System.out.println("商品品種"+statistics.getCount()+"商品總花費"+statistics.getSum()+"商品平均花費"+statistics.getAverage()+"最高花費"+statistics.getMax()+"最低花費"+statistics.getMin());
}
}
參考<<第一行程式碼>>第13章