一 Stream
1.1 stream的概述
stream 是java8的新特性,用于操作java中list,set,map等存储结合中的元素。
1.stream 自己不会存储元素
2.stream不会改变源对象,相反,他们会返回一个持有结果的新stream。
3.stream操作是延迟执行的,也就是说等到有结果的时候才执行。
1.2 stream的操作
1 首先创建stream:从一个数据源中,如集合或者数组中,获取一个流。
2.中间操作:中间采用过滤,分组等操作对数据进行操作。
3.结束操作:将执行的结果产生结果。
1.3 常用api
//1.map 映射,将流中的每一个元素 T 映射为 R(类似类型转换
二 stream的操作
说明:以下演示操作,需要一些数据的支持,本案例自己模拟了一部分数据,见下:
public class StudentDb {
public static List<Student> stuList=new ArrayList<>();
static{
stuList.add(new Student("beijing",23,90.34,"2021-10-04"));
stuList.add(new Student("tianjin",34,30.34,"2021-09-04"));
stuList.add(new Student("shanghai",56,45.24,"2022-10-04"));
stuList.add(new Student("tianjin",89,70.89,"2021-06-03"));
stuList.add(new Student("shenzhen",95,95.89,"2022-10-03"));
stuList.add(new Student(45,89.89,"2022-07-03"));
}
}
2.1 创建stream
public static void createStream(){
//1.通过list转成stream
List<String> dataList=new ArrayList<>();
Stream<String> s=dataList.stream();
System.out.println("s:"+s);
//2.通过数组
List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
Stream<String> stream = strList.stream();
System.out.println("str:"+stream.count());
//3.stream类中的静态方法
Stream<List<String>> stream2= Stream.of(dataList);
System.out.println("ss:"+stream2);
//4.创建无限流
Stream<Integer> stream3= Stream.iterate(0,(x)->{return x+2;});
System.out.println("ss:"+stream3.limit(3));
}
2.2 遍历list
/**
* @author liujianfu
* @description 遍历
* @date 2022/11/1 11:12
* @param []
* @return void
*/
public static void bianli(){
List<Student> stuList= StudentDb.stuList;
//遍历1
stuList.stream().collect(Collectors.toList()).forEach((x)->{System.out.println(x);});
//遍历2
stuList.forEach(System.out::println);
Map<String,Integer> rMap=new HashMap<String,Integer>();
rMap.put("bj",1);
rMap.put("sh",3);
rMap.forEach((k,v)->{System.out.println("k:"+k+" v:"+v);});
}
案例2: 遍历list :
dataList.forEach((x)->{System.out.println("x:"+x);});
public class Test {
public static void main(String[] args) {
List<String> dataList=new ArrayList<String>();
dataList.add("beijing");
dataList.add("shanghai");
dataList.add("zhengzhou");
dataList.forEach((x)->{System.out.println("x:"+x);});
}
}
2.3 封装数据
2.4 切片和过滤
/**
* @author liujianfu
* @description 切边和过滤
* @date 2022/10/31 17:56
* @param []
* @return void
*/
public static void operateQiePianAndFilter(){
//1.filter 过滤掉信息,
List<Student> stuList= StudentDb.stuList;
//过滤掉姓名为shenzhen的数据
stuList.stream().filter((e)->{return !"shenzhen".equals(e.getName());}).forEach((x)->{System.out.println("x:"+x);});
System.out.println("========");
//2.limit 截断流
stuList.stream().filter((e)->{return !"shenzhen".equals(e.getName());}).limit(2).forEach((x)->{System.out.println("x:"+x);});
System.out.println("=========");
//3.skip 跳过n个元素
stuList.stream().filter((e)->{return !"shenzhen".equals(e.getName());}).skip(3).forEach((x)->{System.out.println("x:"+x);});
System.out.println("=====");
//4.distinct,通过每个元素的去重字段进行重写的hashcode和equals进行去重,这里将name字段进行equals和hashcode进行重写
stuList.stream().distinct().forEach((x)->{System.out.println("x:"+x);});
}
2.5 映射
/**
* @author liujianfu
* @description 数据映射
* @date 2022/10/31 19:02
* @param []
* @return void
*/
public static void operateDataMapping(){
//1.map 映射,将流中的每一个元素 T 映射为 R(类似类型转换)
List<Student> stuList= StudentDb.stuList;
stuList.stream().map((x)->{return x.getName();}).forEach(System.out::println);
System.out.println("=====");
//2. flatmap,将流中的每一个元素 T 映射为一个流,再把每一个流连接成为一个流
List<String> list = new ArrayList<>();
list.add("aaa bbb ccc");
list.add("ddd eee fff");
list.add("ggg hhh iii");
list = list.stream().map(s -> s.split(" ")).
flatMap(Arrays::stream).collect(Collectors.toList());
list.stream().forEach(System.out::println);
}
2.6 排序
/**
* @author liujianfu
* @description 排序
* @date 2022/11/1 10:18
* @param []
* @return void
*/
public static void sortData(){
List<Student> stuList= StudentDb.stuList;
//默认排序
stuList.stream().map((s)->{return s.getName()==null?"www":s.getName();})
.sorted()
.forEach(System.out::println);
//先按年龄排序,年龄相等,按姓名
stuList.stream()
.sorted((x, y) -> {
if(x.getAge() == y.getAge()){
return x.getName().compareTo(y.getName());
}else{
return Integer.compare(x.getAge(), y.getAge());
}
}).forEach(System.out::println);
}
2.7 查找和匹配
/**
* @author liujianfu
* @description 匹配
* @date 2022/11/1 10:20
* @param []
* @return void
*/
public static void chazhaoAndPiPei(){
List<Student> stuList= StudentDb.stuList;
//是否匹配
boolean f1=stuList.stream().allMatch((e)->{return e.getName().equals("tianjing");});
System.out.println("f1:"+f1);
boolean f2=stuList.stream().anyMatch((e)->{return "tianjin".equals(e.getName());});
System.out.println("f1:"+f2);
//检查是否没有匹配的元素
boolean f3=stuList.stream().noneMatch((e)->{return"tianjing".equals(e.getName());});
System.out.println("f1:"+f3);
System.out.println("====================");
//获取第一个元素
Optional<Student> op = stuList.stream()
.sorted((e1, e2) -> Double.compare(e1.getScore(), e2.getScore()))
.findFirst();
System.out.println(op.get());
//获取个数,最大值,最小值
long s= stuList.stream().map((x)->{return x.getScore();}).count();
Optional<Double> op2 =stuList.stream().map((x)->{return x.getScore();}).max( (x,y)->{return Double.compare(x,y);});
Optional<Double> op3= stuList.stream().map(Student::getScore).max(Double::compare);
Optional<Student> op4 =stuList.stream().min((x,y)->{ return Double.compare(x.getScore(),y.getScore());});
System.out.println("geshu:"+s+" 最大值:"+op2.get()+" 最大值:"+op3.get()+" 最小值:"+op4.get());
}
2.8 聚合函数(count,sum,max,min,avg)
/**
* @author liujianfu
* @description 求5大聚合函数
* @date 2022/11/1 15:42
* @param []
* @return void
*/
public static void getFiveFunction(){
List<Student> stuList= StudentDb.stuList;
System.out.println("方式1:................");
long s= stuList.stream().map((x)->{return x.getScore();}).count();
Optional<Double> op2 =stuList.stream().map((x)->{return x.getScore();}).max( (x,y)->{return Double.compare(x,y);});
Optional<Double> op3= stuList.stream().map(Student::getScore).max(Double::compare);
Optional<Student> op4 =stuList.stream().min((x,y)->{ return Double.compare(x.getScore(),y.getScore());});
System.out.println("geshu:"+s+" 最大值:"+op2.get()+" 最大值:"+op3.get()+" 最小值:"+op4.get());
System.out.println("方式2:................");
Optional<Double> max = stuList.stream().map(Student::getScore).collect(Collectors.maxBy(Double::compare));
Optional<Double> op = stuList.stream().map(Student::getScore).collect(Collectors.minBy((x,y)->{ return Double.compare(x,y);}));
Optional<Student> st = stuList.stream().collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getScore(), e2.getScore())));
Double sum = stuList.stream().collect(Collectors.summingDouble(Student::getScore));
Double avg =stuList.stream().collect(Collectors.averagingDouble(Student::getScore));
Long count = stuList.stream().collect(Collectors.counting());
System.out.println("条数:"+count+" 最大值:"+max+" 最小值:"+op+" 和:"+sum+" 平均值:"+avg+"st:"+st);
System.out.println("--------------------------------------------");
}
2.9 分组
/**
* @author liujianfu
* @description 分组
* @date 2022/11/1 15:44
* @param []
* @return void
*/
public static void groupbyZiduan(){
List<Student> stuList= StudentDb.stuList;
Map<String, List<Student>> map = stuList.stream().filter((e)->{return e.getName()!=null;})
.collect(Collectors.groupingBy(Student::getName));
map.forEach((k,v)->{System.out.println("k:"+k+" v:"+v);});
Map<Double, Map<String, List<Student>>> map2 = stuList.stream().collect(Collectors.groupingBy(Student::getScore, Collectors.groupingBy((e) -> {
if(e.getAge() >= 60)
return "老年";
else if(e.getAge() >= 35)
return "中年";
else
return "成年";
})));
System.out.println("map2:"+map2);
}
截图:
2.10 分区
/**
* @author liujianfu
* @description 分区
* @date 2022/11/1 16:03
* @param []
* @return void
*/
public static void fenqu(){
List<Student> stuList= StudentDb.stuList;
Map<Boolean, List<Student>> stMap= stuList.stream().collect(Collectors.partitioningBy((e) -> e.getScore() >= 60));
System.out.println("st:"+stMap);
}
截图如下:分为两部分,满足和不满足
2.11 拼接字符串
/**
* @author liujianfu
* @description 拼接字符串
* @date 2022/11/1 16:27
* @param []
* @return void
*/
public static void joinZifuchuan(){
List<Student> stuList= StudentDb.stuList;
String str = stuList.stream().map(Student::getName).collect(Collectors.joining("," , "----", "----"));
System.out.println(str);
}