目录
1.获取Stream流
2.Stream流常见的中间方法
3.Stream流常见的终结方法
1、 Stream 是什么?有什么作用?结合了什么技术?
●也叫 Stream 流,是Jdk8开始新增的一套 API ( java . util . stream .*),可以用于操作集合或者数组的数据。.
优势: Stream 流大量的结合了 Lambda 的语法风格来编程,提供了一种更加强大更加简单的方式操作集合或者数组中的数据,代码更简洁,可读性更好。
2、说说 Stream 流处理数据的步骤是什么?
package com.xinbao.d8_stream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class StreamTest1 {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
Collections.addAll(names,"张三丰", "张无忌", "周芷若", "赵敏", "张强");
System.out.println(names);
//找出姓张且是三个字的名字,存到新集合中去
List<String> list = new ArrayList<>();
for (String name : names) {
if (name.startsWith("张") && name.length() == 3){
list.add(name);
}
}
System.out.println(list);
//使用Stream流解决问题
List<String> list2 = names.stream().filter(s -> s.startsWith("张"))
.filter(a -> a.length() == 3).collect(Collectors.toList());
System.out.println(list2);
}
}
E:\JVsoft\Java\jdk-17\bin\java.exe -javaagent:E:\JVsoft\IntelliJIDEA2021.1.1\lib\idea_rt.jar=4519:E:\JVsoft\IntelliJIDEA2021.1.1\bin -Dfile.encoding=UTF-8 -classpath E:\JVsoft\code\out\production\collection-map-stream-app com.xinbao.d8_stream.StreamTest1
[张三丰, 张无忌, 周芷若, 赵敏, 张强]
[张三丰, 张无忌]
[张三丰, 张无忌]
1.获取Stream流
package com.xinbao.d8_stream;
import java.util.*;
import java.util.stream.Stream;
public class StreamTest2 {
public static void main(String[] args) {
//1.如何获取List集合的Stream流
List<String> names = new ArrayList<>();
Collections.addAll(names,"张三丰", "张无忌", "周芷若", "赵敏", "张强");
Stream<String> stream = names.stream();
//2.如何获取Set集合的Stream流
Set<String> set = new HashSet<>();
Collections.addAll(set,"刘德华", "张曼玉", "张国荣", "刘嘉玲", "王祖贤");
Stream<String> stream1 = set.stream();//alt + enter
stream1.filter(s -> s.contains("张")).forEach(s -> System.out.println(s));
//3.如何获取Map集合的Stream流
Map<String,Double> map = new HashMap<>();
map.put("古力娜扎", 167.5);
map.put("迪丽热巴", 164.5);
map.put("马尔扎哈", 187.7);
map.put("哈尼克孜", 163.8);
Set<String> keys = map.keySet();
Stream<String> ks = keys.stream();
Collection<Double> values = map.values();
Stream<Double> vs = values.stream();
Set<Map.Entry<String, Double>> entries = map.entrySet();
Stream<Map.Entry<String, Double>> kvs = entries.stream();
kvs.filter(s -> s.getKey().contains("哈")).
forEach(s -> System.out.println(s.getKey() + "-->" + s.getValue()));
//4.如何获取数组的Stream流
String[] names2 = {"刘德华", "张曼玉", "张国荣", "刘嘉玲", "王祖贤"};
Stream<String> stream2 = Arrays.stream(names2);
Stream<String> names21 = Stream.of(names2);
}
}
E:\JVsoft\Java\jdk-17\bin\java.exe -javaagent:E:\JVsoft\IntelliJIDEA2021.1.1\lib\idea_rt.jar=39123:E:\JVsoft\IntelliJIDEA2021.1.1\bin -Dfile.encoding=UTF-8 -classpath E:\JVsoft\code\out\production\collection-map-stream-app com.xinbao.d8_stream.StreamTest2
张国荣
张曼玉
马尔扎哈-->187.7
哈尼克孜-->163.8
2.Stream流常见的中间方法
package com.xinbao.d6_map_impl;
import java.util.Objects;
public class Student implements Comparable<Student>{
private String name;
private int age;
private double height;
//this o
@Override
// public int compareTo(Student o) {
// return this.age - o.age;//年龄升序
// }
public int compareTo(Student o) {
return o.age - this.age;
}
public Student() {
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Double.compare(student.height, height) == 0 && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age, height);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", height=" + height +
'}';
}
public Student(String name, int age, double height) {
this.name = name;
this.age = age;
this.height = height;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
}
package com.xinbao.d8_stream;
import com.xinbao.d6_map_impl.Student;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
public class StreamTest3 {
public static void main(String[] args) {
List<Double> scores = new ArrayList<>();
Collections.addAll(scores,88.5,22.5,88.7,56.9,24.8,46.7,96.3);
//需求1:找出成绩大于60的数据,排序输出
scores.stream().filter(s -> s>60).sorted().forEach(s -> System.out.println(s));
List<Student> students = new ArrayList<>();
students.add(new Student("蜘蛛精", 25, 168.5));
students.add(new Student("蜘蛛精", 25, 168.5));
students.add(new Student("至尊宝", 23, 163.5));
students.add(new Student("牛魔王", 28, 183.5));
System.out.println(students);
//需求2:找出年龄大于23小于30的学生,升序输出
students.stream().filter(s -> s.getAge() > 23 && s.getAge() < 30)
.sorted((o1,o2) -> o1.getAge() - o2.getAge()).forEach(System.out::println);
//需求3:取出身高最高的前三名学生,并输出
System.out.println("-------------------------------------------------------------");
students.stream().sorted((o1, o2) -> Double.compare(o2.getHeight(),o1.getHeight()))
.limit(3).forEach(System.out::println);
//需求4:取出身高倒数的两名学生输出
System.out.println("-------------------------------------------------------------");
students.stream().sorted((o1,o2) -> Double.compare(o2.getHeight(),o1.getHeight()))
.skip(students.size() - 2).forEach(System.out::println);
//需求5:找出身高超过168的学生名字,去重再输出
System.out.println("--------------------------------------------------------------");
students.stream().filter(s -> s.getHeight()>168).map(Student::getName)//.map(s->s.getName) 映射
.distinct().forEach(System.out::println);
//distinct去重复,自定义类型的对象(希望内容一样就认为重复,重写hashCode,equals)
students.stream().filter(s -> s.getHeight()>168).distinct().forEach(System.out::println);
Stream<String> ls = Stream.of("李四", "王五", "刘六六");
Stream<String> zs = Stream.of("张三");
Stream<String> concat = Stream.concat(ls, zs);
concat.forEach(System.out::println);
}
}
E:\JVsoft\Java\jdk-17\bin\java.exe -javaagent:E:\JVsoft\IntelliJIDEA2021.1.1\lib\idea_rt.jar=26802:E:\JVsoft\IntelliJIDEA2021.1.1\bin -Dfile.encoding=UTF-8 -classpath E:\JVsoft\code\out\production\collection-map-stream-app com.xinbao.d8_stream.StreamTest3
88.5
88.7
96.3
[Student{name='蜘蛛精', age=25, height=168.5}, Student{name='蜘蛛精', age=25, height=168.5}, Student{name='至尊宝', age=23, height=163.5}, Student{name='牛魔王', age=28, height=183.5}]
Student{name='蜘蛛精', age=25, height=168.5}
Student{name='蜘蛛精', age=25, height=168.5}
Student{name='牛魔王', age=28, height=183.5}
-------------------------------------------------------------
Student{name='牛魔王', age=28, height=183.5}
Student{name='蜘蛛精', age=25, height=168.5}
Student{name='蜘蛛精', age=25, height=168.5}
-------------------------------------------------------------
Student{name='蜘蛛精', age=25, height=168.5}
Student{name='至尊宝', age=23, height=163.5}
--------------------------------------------------------------
蜘蛛精
牛魔王
Student{name='蜘蛛精', age=25, height=168.5}
Student{name='牛魔王', age=28, height=183.5}
李四
王五
刘六六
张三
3.Stream流常见的终结方法
package com.xinbao.d8_stream;
import com.xinbao.d6_map_impl.Student;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamTest4 {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
Student s1 = new Student("蜘蛛精", 25, 168.5);
Student s2 = new Student("蜘蛛精", 25, 168.5);
Student s3 = new Student("至尊宝", 23, 163.5);
Student s4 = new Student("牛魔王", 28, 183.5);
Student s5 = new Student("狐狸精", 23, 161.5);
Student s6 = new Student("白骨精", 25, 161.5);
Collections.addAll(students, s1, s2, s3, s4, s5, s6);
//需求1:计算出高于168的人数
long count = students.stream().filter(s -> s.getHeight() > 168).count();
System.out.println(count);
//需求2:找出最高学生对象并输出
Student max = students.stream().max((o1, o2) -> Double.compare(o1.getHeight(), o2.getHeight())).get();
System.out.println(max);
Optional<Student> max1 = students.stream().max((o1, o2) -> Double.compare(o1.getHeight(), o2.getHeight()));
System.out.println(max1);
//需求3:找出最矮学生对象并输出
Student min = students.stream().min((o1, o2) -> Double.compare(o1.getHeight(), o2.getHeight())).get();
System.out.println(min);
//需求4:找出高于165的学生对象,放到新集合中返回
List<Student> collect = students.stream().filter(s -> s.getHeight() > 165).collect(Collectors.toList());
System.out.println(collect);
Set<Student> collect2 = students.stream().filter(s -> s.getHeight() > 165).collect(Collectors.toSet());
System.out.println(collect2);//去重
//流只能收集一次(类比迭代器)
// Stream<Student> str = students.stream().filter(s -> s.getHeight() > 165);
// List<Student> list = str.collect(Collectors.toList());
// System.out.println(list);
// Set<Student> set = str.collect(Collectors.toSet());//报错,流已经终结
// System.out.println(set);
//需求五:找出高于165的学生对象,并把对象的名字和身高,存入到一个Map集合返回
Map<String,Double> map =
students.stream().filter(s -> s.getHeight()>165)//不会自动去重,需要.distinct()去重
.distinct().collect(Collectors.toMap(a -> a.getName(), a -> a.getHeight()));
System.out.println(map);
Object[] objects = students.stream().filter(s -> s.getHeight() > 165).toArray();
System.out.println(Arrays.toString(objects));
Student[] students1 = students.stream().filter(s -> s.getHeight() > 165).toArray(len -> new Student[len]);
System.out.println(Arrays.toString(students1));
}
}
E:\JVsoft\Java\jdk-17\bin\java.exe -javaagent:E:\JVsoft\IntelliJIDEA2021.1.1\lib\idea_rt.jar=27234:E:\JVsoft\IntelliJIDEA2021.1.1\bin -Dfile.encoding=UTF-8 -classpath E:\JVsoft\code\out\production\collection-map-stream-app com.xinbao.d8_stream.StreamTest4
3
Student{name='牛魔王', age=28, height=183.5}
Optional[Student{name='牛魔王', age=28, height=183.5}]
Student{name='狐狸精', age=23, height=161.5}
[Student{name='蜘蛛精', age=25, height=168.5}, Student{name='蜘蛛精', age=25, height=168.5}, Student{name='牛魔王', age=28, height=183.5}]
[Student{name='牛魔王', age=28, height=183.5}, Student{name='蜘蛛精', age=25, height=168.5}]
{蜘蛛精=168.5, 牛魔王=183.5}
[Student{name='蜘蛛精', age=25, height=168.5}, Student{name='蜘蛛精', age=25, height=168.5}, Student{name='牛魔王', age=28, height=183.5}]
[Student{name='蜘蛛精', age=25, height=168.5}, Student{name='蜘蛛精', age=25, height=168.5}, Student{name='牛魔王', age=28, height=183.5}]
进程已结束,退出代码为 0