Stream流
Stream流的概述
- 在Java 8 中,得益于Lambda所带来的函数式编程,引入了一个全新的Stream流概念
- 目的:用于简化集合和数组操作的API
/**
* 目标:初步体验Stream流的方便与快捷
*/
public class StreamTest {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
Collections.addAll(names,"张三丰","张无忌","周芷若","赵敏","张强");
System.out.println(names);
// 1.从集合中找出姓张的放到新集合
List<String> zhangList = new ArrayList<>();
for (String name : names) {
if (name.startsWith("张")){
zhangList.add(name);
}
}
System.out.println(zhangList);
// 2.找名称长度是3的姓名
List<String> zhangThreeList = new ArrayList<>();
for (String name : zhangList) {
if (name.length() ==3){
zhangThreeList.add(name);
}
}
System.out.println(zhangThreeList);
// 3.使用Stream实现
names.stream().filter(s -> s.startsWith("张")).filter(s -> s.length()==3).forEach(s -> System.out.println(s));
}
}
Stream流的思想
Stream流的获取
Stream流的三类方法
- 获取Stream流
- 创建一条流水线,并把数据放到流水线上准备进行操作
- 中间方法
- 流水线上的操作。一次操作完毕之后,还可以继续进行其他操作
- 终结方法
- 一个Stream流只能有一个终结方法,是流水线上的最后一个操作
Stream操作集合或者数组的第一步是先得到Stream流,然后才能使用流的功能
集合获取Stream流的方式
-
可以使用Collection接口中的默认方法stream()生成流
数组获取Stream流的方式
public class StreamDemo2 {
public static void main(String[] args) {
/** ---------------------Collection集合获取流----------------*/
Collection<String> list = new ArrayList<>();
Stream<String> s = list.stream();
/** ---------------------Map集合获取流----------------*/
Map<String, Integer> maps = new HashMap<>();
// 键流
Stream<String> keyStream = maps.keySet().stream();
// 值流
Stream<Integer> valuesStream = maps.values().stream();
// 键值对流(拿整体)
Stream<Map.Entry<String, Integer>> entryStream = maps.entrySet().stream();
/** ---------------------数组获取流----------------*/
String[] names = {"赵敏","小昭","灭绝","周芷若"};
Stream<String> nameStream = Arrays.stream(names);
Stream<String> nameStream2 = Stream.of(names);
}
}
Stream流的常用API
中间操作方法(非终结方法)
注意:
- 中间方法也称为非终结方法,调用完成后返回新的Stream流可以继续使用,支持链式编程
- 在Stream流中无法直接修改集合、数组中的数据
Stream流中常见终结操作方法
注意:终结操作方法,调用完成后流就无法继续使用了,原因是不会返回Stream了
/**
目标:Stream流的常用API
forEach:逐一处理(遍历)
count:统计个数
-- long count();
filter : 过滤元素
-- Stream<T> filter(Predicate<? super T> predicate)
limit : 取前几个元素
skip : 跳过前几个元素
map : 加工方法
concat : 合并流
*/
public class StreamDemo3 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌","周芷若","赵敏","张强","张三丰","张三丰");
//Stream<T> filter(Predicate<? super T> predicate);
list.stream().filter(s -> s.startsWith("张")).forEach(s -> System.out.println(s));
long size = list.stream().filter(s -> s.length() == 3).count();
System.out.println(size);
list.stream().filter(s -> s.startsWith("张")).limit(2).forEach(s -> System.out.println(s));
list.stream().filter(s -> s.startsWith("张")).limit(2).forEach(System.out::println);//效果与上面相同
list.stream().filter(s -> s.startsWith("张")).skip(2).forEach(s -> System.out.println(s));
list.stream().distinct().forEach(s -> System.out.println(s));
// map加工方法 : 第一个参数是 原材料 -> 第二个参数是 加工后的结果
// 给集合元素的前面都加上一个:黑马的
list.stream().map(s -> "黑马的:"+s).forEach(System.out::println);
// 需求:把所有的名称,都加工成一个学生对象
// 需创建一个学生类包含name属性,有get/set、toString方法、有参/无参构造器
list.stream().map(s -> new Student(s)).forEach(s-> System.out.println(s));
list.stream().map(Student::new).forEach(System.out::println); //构造器引用 方法引用
// 合并流
Stream<String> s1 = list.stream().filter(s -> s.startsWith("张"));
Stream<String> s2 = Stream.of("Java1","Java2");
Stream<String> s3 = Stream.concat(s1, s2);
s3.forEach(s -> System.out.println(s));
}
}
Stream流的综合应用
Test类
public class Test {
private static double allMoney;
private static double allMoney1;
private static double allMoney2;
public static void main(String[] args) {
List<Employee> one = new ArrayList<>();
one.add(new Employee("孙悟空",'男',25000,1000,"顶撞上司"));
one.add(new Employee("猪八戒",'男',30000,25000,null));
one.add(new Employee("沙僧",'男',20000,20000,null));
one.add(new Employee("小白龙",'男',20000,25000,null));
List<Employee> two = new ArrayList<>();
two.add(new Employee("武松",'男',15000,9000,null));
two.add(new Employee("李逵",'男',20000,10000,null));
two.add(new Employee("西门庆",'男',50000,10000,"被打"));
two.add(new Employee("潘金莲",'女',3500,1000,"被打"));
two.add(new Employee("武大郎",'女',20000,0,"下毒"));
// 1.a.开发一部的最高工资的员工 //max 根据自定规则找出数据最大值并返回最大值的对象 // get 获取对象
Topperformer t1 = one.stream()
.max((o1, o2) -> Double.compare(o1.getSalary() + o1.getBonus(), o2.getSalary() + o2.getBonus()))
.map(e -> new Topperformer(e.getName(), e.getSalary() + e.getBonus()))
.get();
System.out.println(t1);
// b.开发二部的最高工资的员工
Topperformer t2 = two.stream()
.max((o1, o2) -> Double.compare(o1.getSalary() + o1.getBonus(), o2.getSalary() + o2.getBonus()))
.map(e -> new Topperformer(e.getName(), e.getSalary() + e.getBonus()))
.get();
System.out.println(t2);
// 2.统计平均工资,去掉最高工资和最低工资
// a.开发一部
one.stream()
.sorted((o1, o2) -> Double.compare(o1.getSalary()+o1.getBonus(), o2.getSalary()+o2.getBonus()))
.skip(1).limit(one.size()-2).forEach(e->{
allMoney1 += (e.getSalary()+e.getBonus());
});
System.out.println("开发一部的平均工资是:"+allMoney1/(one.size()-2));
// b.开发二部
two.stream()
.sorted((o1, o2) -> Double.compare(o1.getSalary()+o1.getBonus(), o2.getSalary()+o2.getBonus()))
.skip(1).limit(one.size()-2).forEach(e->{
allMoney2 += (e.getSalary()+e.getBonus());
});
System.out.println("开发二部的平均工资是:"+allMoney2/(one.size()-2));
// 3.合并两个流,再统计
Stream<Employee> s3 = Stream.concat(one.stream(), two.stream());
s3.sorted((o1, o2) -> Double.compare(o1.getSalary()+o1.getBonus(), o2.getSalary()+o2.getBonus()))
.skip(1).limit(one.size()+ two.size()-2)
.forEach(e->{
allMoney += (e.getSalary()+e.getBonus());
});
// BigDecimal 精准
BigDecimal a = BigDecimal.valueOf(allMoney);
BigDecimal b = BigDecimal.valueOf((one.size()+ two.size()-2));
System.out.println("两个开发部门整体的平均工资是:"+a.divide(b,2, RoundingMode.HALF_UP));
}
}
Employee类
public class Employee {
private String name;
private char sex;
private double salary; //工资
private double bonus; //奖金
private String punish; //处罚信息
public Employee() {
}
public Employee(String name, char sex, double salary, double bonus, String punish) {
this.name = name;
this.sex = sex;
this.salary = salary;
this.bonus = bonus;
this.punish = punish;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getBonus() {
return bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
public String getPunish() {
return punish;
}
public void setPunish(String punish) {
this.punish = punish;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", sex=" + sex +
", salary=" + salary +
", bonus=" + bonus +
", punish='" + punish + '\'' +
'}';
}
}
Topperformer类
public class Topperformer {
private String name;
private double money; //月薪
public Topperformer() {
}
public Topperformer(String name, double money) {
this.name = name;
this.money = money;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
@Override
public String toString() {
return "Topperformer{" +
"name='" + name + '\'' +
", money=" + money +
'}';
}
}
收集Stream流
Stream流的收集操作
-
收集Stream流的含义:就是把Stream流操作后的结果数据转回到集合或者数组中去
-
Stream流:方便操作集合/数组的手段
-
集合/数组:才是开发中的目的
Stream流的收集方法
/**
* 目标:收集Stream流的数据到集合或者数组中去
*/
public class StreamDemo4 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌","周芷若","赵敏","张强","张三丰","张三丰");
Stream<String> s1 = list.stream().filter(s -> s.startsWith("张"));
List<String> zhangList = s1.collect(Collectors.toList());
System.out.println(zhangList);
// 注意:注意:注意:流只能使用一次
Stream<String> s2 = list.stream().filter(s -> s.startsWith("张"));
Set<String> zhangSet = s2.collect(Collectors.toSet());
System.out.println(zhangSet);
Stream<String> s3 = list.stream().filter(s -> s.startsWith("张"));
Object[] arrs = s3.toArray();
//String[] arrs = s3.toArray(value -> new String[value]);//可以不管,拓展一下思维
System.out.println("Arrays数组内容:"+ Arrays.toString(arrs));
}
}
标签:Stream,String,stream,new,public,name
From: https://www.cnblogs.com/zzx944964684/p/17008837.html