1、stream()后可调函数
方法名 | 说明 |
---|---|
filter() | 过滤掉一部分元素,剩下符合条件的元素 |
limit() | 取前几个元素,括号里填数字 |
map() | 取实体类里的字段数据 |
reduce() | 归约操作可以将流中元素反复结合起来,得到一个值 |
2、举例说明
实体类Phone
public class Phone {
//品牌
private String brand;
//价格
private Integer price;
public Phone() {
}
public Phone(String brand, Integer price) {
this.brand = brand;
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
}
测试类TestStream
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class TestStream {
public static void main(String[] args) {
Phone phone1 = new Phone("OPPO",2999);
Phone phone2 = new Phone("VIVO",2599);
Phone phone3 = new Phone("华为",4999);
Phone phone4 = new Phone("小米",1999);
Phone phone5 = new Phone("魅族",2399);
List<Phone> phoneList = new ArrayList<>();
phoneList.add(phone1);
phoneList.add(phone2);
phoneList.add(phone3);
phoneList.add(phone4);
phoneList.add(phone5);
// //验证filter(),筛选手机价格大于2600的手机,输出OPPO,华为
// phoneList = phoneList.stream().filter(p -> p.getPrice() > 2600).collect(Collectors.toList());
// //验证limit(),截取前3条数据,输出OPPO,VIVO,华为
// phoneList = phoneList.stream().limit(3).collect(Collectors.toList());
// //验证filter(),limit()连用,输出OPPO,VIVO
// phoneList = phoneList.stream().filter(p -> p.getPrice() > 2000).limit(2).collect(Collectors.toList());
// //验证map取实体里字段值,输出2999,2599,4999,1999,2399 (下面是两种用法,结果相同)
// List<Integer> priceList = phoneList.stream().map(p -> p.getPrice()).collect(Collectors.toList());
// List<Integer> priceList = phoneList.stream().map(Phone::getPrice).collect(Collectors.toList());
// priceList.forEach(p -> System.out.println(p));
// //验证reduce(),求价格总和,输出14995,orElse是当list里没有元素时,输出0
// Integer totalPrice = phoneList.stream().map(Phone::getPrice).reduce((a, b) -> a + b).orElse(0);
// System.out.println(totalPrice);
phoneList.forEach(p -> System.out.println(p.getBrand()));
}
}