Map是流中的一个中间操作。返回流。地图法java.util.stream.Stream类接受函数类型的参数,下面的代码计算流中图书的总价。
在BookStoreFacade类的getTotalPrice方法中使用map操作返回价格流。Map方法返回Stream。然后在Stream上调用forEach方法来获取所有书籍的价格之和。
class Book {
private String publisher;
private String author;
private String name;
private float price;
public Book(String name, String author, float price,
String publisher) {
this.name = name;
this.author = author;
this.price = price;
this.publisher = publisher;
}
public float getPrice() {
return price;
}
public String toString() {
return "Title: " + name
+ ", Author: " + author
+ ", Price: " + price
+ ", Publisher: " + publisher;
}
}
class BookStoreFacade {
private float totalPrice;
public float getTotalPrice(Stream<Book> bookStream) {
totalPrice = 0;
<strong> bookStream.map(b -> b.getPrice())</strong>
<strong>.forEach(price -> totalPrice += price);
</strong> return totalPrice;
}
}
class Main {
public static void main(String args[]) {
List<Book> books = new ArrayList<>();
books.add(new Book("You can win", "Shiv Khera", 75,
"Bloomsbury Publishing"));
books.add(new Book("Indian Ethics", "Shyam Ranganathan",
2807, "Bloomsbury Publishing"));
BookStoreFacade bookstore =new BookStoreFacade();
System.out.println("Total Price : "
+ bookstore.getTotalPrice(books.stream()));
}
}
代码1.流中地图操作的使用
|