目录
1.什么是Stream
Stream 是Java8中处理集合的关键抽象概念,它可以对集合进行非常复杂的查找、过滤、筛选等操作。
2.为什么使用Stream
当我们需要对集合中的元素进行操作的时候,除了必需的添加、删除、获取外,最典型的就是集合遍历。
例如:一个ArrayList集合中存储数据;需求:1.拿到所有姓张的 2.拿到名字长度为3个字的 3.打印这些数据,此时代码:
public class My {
public static void main(String[] args) {
// 一个ArrayList集合中存储有以下数据:张无忌,周芷若,赵敏,张强,张三丰
// 需求:1.拿到所有姓张的 2.拿到名字长度为3个字的 3.打印这些数据
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "张一一","张一","张二二","王一","李一","张三");
// 1.拿到所有姓张的
ArrayList<String> zhangList = new ArrayList<>();
for (String name : list) {
if (name.startsWith("张")) {
zhangList.add(name);
}
}
// 2.拿到名字长度为3个字的
ArrayList<String> threeList = new ArrayList<>();
for (String name : zhangList) {
if (name.length() == 3) {
threeList.add(name);
}
}
// 3.打印这些数据
for (String name : threeList) {
System.out.println(name);
}
}
}
这段代码中含有三个循环,每一个作用不同:
首先筛选所有姓张的人;
然后筛选名字有三个字的人;
最后进行对结果进行打印输出。
每当我们需要对集合中的元素进行操作的时候,总是需要进行循环、循环、再循环。这是理所当然的么?不是。循环 是做事情的方式,而不是目的。每个需求都要循环一次,还要搞一个新集合来装数据,如果希望再次遍历,只能再使用另一个循环从头开始。
使用Stream流来改写代码:
public class OpenTest {
public static void main(String[] args) {
List<String> list=new ArrayList<>();
Collections.addAll(list,"张一一","张一","张二二","王一","李一","张三");
list.stream()
//底层使用断言函数式,有参有boolean返回值
.filter((item)->item.startsWith("张"))
.filter(item->item.length()==3)
.forEach(item-> System.out.println(item));
}
}
对集合的操作语法简洁:性能比传统快。
3.Stream流的操作原理
注意:Stream和IO流(InputStream/OutputStream)没有任何关系,请暂时忘记对传统IO流的固有印象!
Stream流式思想类似于工厂车间的“生产流水线”,Stream流不是一种数据结构,不保存数据,而是对数据进行加工处理。Stream可以看作是流水线上的一个工序。在流水线上,通过多个工序让一个原材料加工成一个商品。
Stream不存在数据,只对数据进行加工处理。
4.如何获取Stream流对象
(1)通过Collection对象的stream()或parallelStream()方法
(2)通过Arrays类的stream()方法
(3)通过Stream接口的of()、iterate()、generate()方法
(4)通过IntStream、LongStream、DoubleStream接口中的of、range、rangeClosed方法
练习代码展示:
public class getStreamMethods {
public static void main(String[] args) {
//通过集合对象调用stream()获取流
List<String> list=new ArrayList<>();
Collections.addAll(list,"张三","李四","王五","赵六");
Stream<String> stream = list.stream();
//通过Arrays数组工具类获取Stream对象
int[] arr={3,45,23,33,67};
IntStream stream1 = Arrays.stream(arr);
//使用Stream类中of方法
Stream.of("hello","world","spring","java");
//LongStream range不包括右侧
//LongStream rangeClosed包括右侧
LongStream range = LongStream.range(1, 10);
range.forEach(item-> System.out.println(item));
//上面都是获取的串行流。 还可以获取并行流。如果流中的数据量足够大,并行流可以加快处理速度
Stream<String> stringStream = list.parallelStream();
stringStream.forEach(item-> System.out.println(item));
//或者是此款样式输出信息
//stringStream.forEach(System.out::println);
}
}
5.Stream流中常见的api
中间操作api: 一个操作的中间链,对数据源的数据进行操作。而这种操作的返回类型还是一个Stream对象。
终止操作api: 一个终止操作,执行中间操作链,并产生结果,返回类型不在是Stream流对象。
(1)filter / foreach / count
(2) map | sorted
map--接收Lambda,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
//对流中元素排序
personList.stream()
.sorted((o1,o2)->o1.getAge()-o2.getAge())
.forEach(System.out::println);
//集合中每个元素只要名.map--->原来流中每个元素转换为另一种格式。
// personList.stream()
// .map(item->{
// Map<String,Object> m=new HashMap<>();
// m.put("name",item.getName());
// m.put("age",item.getAge());
// return m;
// })
// .forEach(System.out::println);
(3) min max
(4)规约reduce
(5)collect搜集 match find
总代码展示:
public class GetStreamApi {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person("欧阳雪",18,"中国",'F'));
personList.add(new Person("Tom",24,"美国",'M'));
personList.add(new Person("Harley",22,"英国",'F'));
personList.add(new Person("向天笑",20,"中国",'M'));
personList.add(new Person("李康",22,"中国",'M'));
personList.add(new Person("小梅",20,"中国",'F'));
personList.add(new Person("何雪",21,"中国",'F'));
personList.add(new Person("李康",22,"中国",'M'));
//findFirst(找第一个出现的符合要求的Person类) match
Optional<Person> first = personList.stream()
.filter(item -> item.getSex() == 'F')
.findFirst();
System.out.println(first);
System.out.println("=================================================");
//findAny(找随机出现的符合要求的Person类,注意使用并发类) match
Optional<Person> any = personList.parallelStream()
.filter(item -> item.getSex() == 'M')
.findAny();
System.out.println(any);
System.out.println("=====================================================");
//match: allMatch 符合前边条件的同时又符合现在条件的所有Person类 为true
//match: anyMatch 符合前边条件的同时又符合现在条件的任一Person类 为true
//match: noneMatch 符合前边条件的同时不符合现在条件的任一Person类 为true
boolean b1 = personList.stream()
.filter(item -> item.getSex() == 'F').allMatch(item -> item.getAge() >= 20);
System.out.println(b1);
System.out.println("===========================================");
//搜索方法collect 属于终止方法
//年龄大于20且性别为M
List<Person> collect = personList.stream()
.filter(item -> item.getAge() > 20)
.filter(item -> item.getSex() == 'M')
.collect(Collectors.toList());
System.out.println(collect);
System.out.println("====================================");
//求集合中所有人的年龄和 参数和返回类型必须一致
Optional<Integer> reduce = personList.stream()
.map(item -> item.getAge())
.reduce((a, b) -> a + b);
System.out.println(reduce.get());
System.out.println("====================================");
//求集合中所有人的年龄和+10 参数和返回类型必须一致
Integer reduce1 = personList.stream()
.map(item -> item.getAge())
.reduce(10, (a, b) -> a + b);
System.out.println(reduce1);
System.out.println("====================================");
//求名字最长的员工
Optional<Person> max1 = personList.stream()
.max((o1, o2) -> o1.getName().length() - o2.getName().length());
System.out.println(max1.get());
System.out.println("===================================");
//查找最大年龄的人,max终止操作
Optional<Person> max = personList.stream().max((o1, o2) -> o1.getAge() - o2.getAge());
System.out.println(max.get());
System.out.println("===================================");
//查找最小年龄的人,min终止操作
Optional<Person> min = personList.stream().min((o1, o2) -> o1.getAge() - o2.getAge());
System.out.println(min.get());
System.out.println("===================================");
//集合中每个元素只要名及年龄,map---》原来流中每个元素转换为另一种格式
personList.stream()
.map(item->{
Map<String,Object> m=new HashMap<>();
m.put("name",item.getName());
m.put("age",item.getAge());
return m;
})
.forEach(System.out::println);
//对流中元素排序
personList.stream()
.sorted((o1,o2)->o1.getAge()-o2.getAge())
.forEach(System.out::println);
System.out.println("===============================================");
//找到年龄大于18的并输出 ; filter()过滤器需要一个断言接口函数,断言接口返回true,获取该元素 , forEach()遍历
//无论执行多少个中间操作,如果没有执行终止操作,那么 中间操作都不会被执行
personList.stream()
.filter(item->item.getAge()>18)
.forEach(System.out::println);
//找出所有中国人的数量 filter()过滤器,过滤其他国家的人 count()终止操作
long count = personList.stream().filter(item -> item.getCountry().equals("中国")).count();
System.out.println(count);
//找到性别M的并输出 ; filter()过滤器需要一个断言接口函数,断言接口返回true,获取该元素 ,
long count1 = personList.stream().filter(item -> item.getSex() == 'M').count();
System.out.println(count1);
}
}
class Person {
private String name;
private Integer age;
private String country;
private char sex;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", country='" + country + '\'' +
", sex=" + sex +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public Person(String name, Integer age, String country, char sex) {
this.name = name;
this.age = age;
this.country = country;
this.sex = sex;
}
}
6.新增了日期时间类
旧的日期时间的缺点:
设计比较乱: Date日期在java.util和java.sql也有,而且它的时间格式转换类在java.text包。
线程不安全。
新增加了哪些类?
LocalDate:表示日期类。yyyy-MM-dd
LocalTime:表示时间类。HH:mm:ss
LocalDateTime:表示日期时间类yyyy-MM-dd t HH:mm:ss sss
DatetimeFormatter:日期时间格式转换类。
Instant:时间戳类
Duration:用于计算两个日期类
代码展示:
public class NewDateTest {
public static void main(String[] args) {
LocalDate now1 = LocalDate.now();//获取当前日期时间
System.out.println(now1);
LocalDate now2 = LocalDate.of(2022, 6, 20);//指定日期
System.out.println(now2);
LocalTime now3 = LocalTime.now();//获取当前日期时间
System.out.println(now3);
LocalTime of = LocalTime.of(17,30,20);//指定时间
System.out.println(of);
LocalDateTime now = LocalDateTime.now();//获取当前日期时间
LocalDateTime of1 = LocalDateTime.of(2022, 7, 1, 20, 15, 20);
Duration between = Duration.between(now, of1);
System.out.println(between.toDays());//两端时间差
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate parse = LocalDate.parse("1992-12-12", dateTimeFormatter);//把字符串转换为日期格式
System.out.println(parse);
}
}