一.什么是Stream?
1.流到底是什么呢?
是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。
“集合讲的是数据,流讲的是计算!”
2.注意:
Stream自己不会存储元素
Stream不会改变源对象。相反,他们会返回一个持有结果的新Stream
Stream操作是延迟执行的。这以为着他们会等到需要结果的时候才执行
二.Stream的操作三个步骤
1.创建Stream
2.中间操作
3.终止操作(终端操作)
1.Stream的4种创建方式
1.可以通过Collection系列集合提供的Stream()或者parallelStream()并行流 获取流
List<String> list = new ArrayList<>();Stream<String> stream = list.stream();
2.可以通过Arrays中的静态方法stream()获取数组流
Employee[] employees = new Employee[10];Stream<Employee> employeeStream = Arrays.stream(employees);
3.通过Stream类中的静态方法of()
Stream<String> stringStream = Stream.of("aa", "bb", "cc");
4.创建无限流
迭代
Stream<Integer> integerStream = Stream.iterate(0, (x) -> x + 2);integerStream.limit(10).forEach(System.out::println);
生成
Stream.generate(() -> Math.random()).limit(5).forEach(System.out::println);
2.Stream的中间操作:
1.筛选与切片
多个中间操作可以谅解起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理!而在终止操作时一次性全部处理,称为“惰性求值”。
filter(Predicate p):接收Lambda,从流中排除某些元素
- distinct():筛选,通过流所生成元素的hashCode()和equals()去排除重复元素。注意:对象需要重写equals和hashcode
- limit(long maxSize):截断流,使其元素不操作给定数量
skip(long n):跳过元素,返回一个扔掉了前n个元素的流。若扔掉的流中元素不足n个,则返回一个空流。与limit(n)互补
//员工集合List<Employee> employeeList = Arrays.asList(new Employee("张三", 18, 6669.58),new Employee("李四", 12, 7779.58),new Employee("王五", 36, 9229.58),new Employee("赵六", 51, 19999.58),new Employee("田七", 20, 3399.58),new Employee("田七", 20, 3399.58),new Employee("田七", 20, 3399.58),new Employee("田七", 20, 3399.58));
```java //filter //内部迭代:迭代操作由Stream API完成 @Test public void test1() {
//中间操作:不会执行任何操作Stream<Employee> employeeStream = employeeList.stream().filter(x -> {System.out.println("Stream API 的中间操作");return (x.getAge() > 35);});//终止操作:一次性执行全部内容,即“惰性求值”employeeStream.forEach(System.out::println);
} //外部迭代 @Test public void test2() {
Iterator<Employee> iterator = employeeList.iterator();while (iterator.hasNext()) {System.out.println(iterator.next());}
} //limit @Test public void test3() {
employeeList.stream().filter((x) -> {System.out.println("短路!");return x.getSalary() > 5000;}).limit(2).forEach(System.out::println);
} //skip @Test public void test4() {
employeeList.stream().filter((x) -> x.getSalary() > 5000).skip(2).forEach(System.out::println);
} //distinct @Test public void test5() {
employeeList.stream().filter((x) -> x.getSalary() > 3000).skip(2).distinct().forEach(System.out::println);
}
<a name="oxrpf"></a>### 2.映射- **map:**接收 Lambda ,将元素转换为其他形式或提取信息;接受一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素```java@Testpublic void test6() {List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");list.stream().map((x) -> x.toUpperCase()).forEach(System.out::println);System.out.println("-------------------------------------------");employeeList.stream().map(Employee::getName).forEach(System.out::println);}
flatMap:接收一个函数作为参数,将流中每一个值都换成另一个流,然后把所有流重新连接成一个流
@Testpublic void test7() {List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");Stream<Stream<Character>> streamStream = list.stream().map(TestStreamAPI2::filterCharacter);streamStream.forEach((x) -> x.forEach(System.out::println));System.out.println("-------------------------------------------");Stream<Character> characterStream = list.stream().flatMap(TestStreamAPI2::filterCharacter);characterStream.forEach(System.out::println);}
3.排序
sorted():自然排序(Comparable)
- sorted(Comparator c):定制排序(Comparator)
@Testpublic void test8() {List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");list.stream().sorted().forEach(System.out::println);System.out.println("-------------------------------------------");employeeList.stream().sorted((x, y) -> {if ((x.getAge() + "").equals(y.getAge() + "")) {return x.getName().compareTo(y.getName());} else {return (x.getAge() + "").compareTo(y.getAge() + "");}}).forEach(System.out::println);}
3.Stream的终止操作:
collect(Collector c):将流转换为其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法。
Collector接口中方法的实现决定了如何对流执行收集操作(如收集到List、Set、Map)。但是Collectors实用类提供了很多静态方法,可以方便地创建常见收集器实例,具体方法与实例如下:
1.查找
- allMatch:检查是否匹配所有元素
- anyMatch:检查是否至少匹配一个元素
- noneMatch:检查是否没有匹配所有元素
- findFirst:返回第一个元素
findAny:返回当前流中的任意元素
@Testpublic void test1() {boolean allMatch = employeeList.stream().allMatch((x) -> x.getStatus() == Status.VOCATION);System.out.println(allMatch);System.out.println("-------------------------------------------");boolean anyMatch = employeeList.stream().anyMatch((x) -> x.getStatus() == Status.VOCATION);System.out.println(anyMatch);System.out.println("-------------------------------------------");boolean noneMatch = employeeList.stream().noneMatch((x) -> x.getStatus() == Status.VOCATION);System.out.println(noneMatch);System.out.println("-------------------------------------------");Optional<Employee> optionalEmployee = employeeList.stream().sorted((x, y) -> Double.compare(x.getSalary(), y.getSalary())).findFirst();System.out.println(optionalEmployee.get());System.out.println("-------------------------------------------");Optional<Employee> any = employeeList.stream().filter((e) -> e.getStatus() == Status.Busy).findAny();System.out.println(any.get());}
2.匹配
count:返回流中元素的总个数
- max:返回流中最大值
min:返回流中最小值
@Testpublic void test2() {long count = employeeList.stream().count();System.out.println(count);System.out.println("-------------------------------------------");Optional<Employee> maxEmployee = employeeList.stream().max((x, y) -> Double.compare(x.getSalary(), y.getSalary()));System.out.println(maxEmployee.get());System.out.println("-------------------------------------------");Optional<Double> min = employeeList.stream().map(Employee::getSalary).min(Double::compare);System.out.println(min.get());}
3.归约
reduce(T identity, BinaryOperator) / reduce(BinaryOperator) 可以将流中的数据反复结合起来,得到一个值
@Testpublic void test3() {List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);Integer reduce = list.stream().reduce(0, (x, y) -> x + y);System.out.println(reduce);System.out.println("-------------------------------------------");Double empReduce = employeeList.stream().map(Employee::getSalary).reduce(0d, (x, y) -> x + y);System.out.println(empReduce);System.out.println("-------------------------------------------");Optional<Double> doubleOptional = employeeList.stream().map(Employee::getSalary).reduce(Double::sum);System.out.println(doubleOptional.get());}
4.收集
collect 将流转换成其他形式;接收一个 Collector 接口的实现,用于给流中元素做汇总的方法
获取属性值集合
@Testpublic void test4() {List<String> collectList = employeeList.stream().map(Employee::getName).collect(Collectors.toList());System.out.println(collectList);System.out.println("-------------------------------------------");Set<String> collectSet = employeeList.stream().map(Employee::getName).collect(Collectors.toSet());System.out.println(collectSet);System.out.println("-------------------------------------------");HashSet<String> collectHashSet = employeeList.stream().map(Employee::getName).collect(Collectors.toCollection(HashSet::new));System.out.println(collectHashSet);}
总数、平均值、总和
@Testpublic void test5() {//总数employeeList.stream().collect(Collectors.counting());//平均值employeeList.stream().collect(Collectors.averagingDouble(Employee::getSalary));//总和employeeList.stream().collect(Collectors.summingDouble(Employee::getSalary));//工资最大的员工信息Optional<Employee> maxEmp = employeeList.stream().collect(Collectors.maxBy((x, y) -> Double.compare(x.getSalary(), y.getSalary())));//工资最小的值Optional<Double> minEmp = employeeList.stream().map(Employee::getSalary).collect(Collectors.minBy(Double::compare));}
分组与多级分组
//分组@Testpublic void test6() {Map<Status, List<Employee>> statusListMap = employeeList.stream().collect(Collectors.groupingBy(Employee::getStatus));System.out.println(statusListMap);}//多级分组@Testpublic void test7() {Map<Status, Map<String, List<Employee>>> collect = employeeList.stream().collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {if (((Employee) e).getAge() <= 35) {return "青年";} else if (((Employee) e).getAge() <= 50) {return "中年";} else {return "老年";}})));}
分区:满足条件的分一个区,不满足条件的分一个区。
@Testpublic void test8() {Map<Boolean, List<Employee>> collect = employeeList.stream().collect(Collectors.partitioningBy((e) -> e.getSalary() > 5000));System.out.println(collect);}
拼接
@Testpublic void test10() {String collect = employeeList.stream().map(Employee::getName).collect(Collectors.joining(",", "[", "]"));System.out.println(collect);}
三.Stream API练习
/***交易人**/@Data@AllArgsConstructor@NoArgsConstructorpublic class Trader {private String name;//姓名private String city;//居住地}/***交易实体**/@Data@NoArgsConstructor@AllArgsConstructorpublic class Transaction {private Trader trader;private int year;//年份private int value;//交易额}
List<Transaction> transactions = null;@BeforeEachpublic void before() {Trader raoul = new Trader("Raoul", "Cambridge");Trader mario = new Trader("Mario", "Milan");Trader alan = new Trader("Alan", "Cambridge");Trader brian = new Trader("Brian", "Cambridge");transactions = Arrays.asList(new Transaction(brian, 2011, 300),new Transaction(raoul, 2012, 1000),new Transaction(raoul, 2011, 400),new Transaction(mario, 2012, 710),new Transaction(mario, 2012, 700),new Transaction(alan, 2012, 950));}//1.找出2011年发生的所有交易,并按照交易额排序,由高到低@Testpublic void test1() {transactions.stream().filter((x) -> x.getYear() == 2011).sorted((x, y) -> -Integer.compare(x.getValue(), y.getValue())).forEach(System.out::println);}//2.交易员都在哪些不同的城市工作过?@Testpublic void test2() {transactions.stream().map(Transaction::getTrader).map(Trader::getCity).distinct().forEach(System.out::println);}//3.查找所有来自剑桥的交易员,并按照姓名排序@Testpublic void test3() {transactions.stream().filter((x) -> x.getTrader().getCity().equals("Cambridge")).map(Transaction::getTrader).distinct().sorted((x, y) -> x.getName().compareTo(y.getName())).forEach(System.out::println);}//4.返回所有交易员的姓名字符串@Testpublic void test4() {String collect = transactions.stream().map(Transaction::getTrader).map(Trader::getName).distinct().collect(Collectors.joining(","));System.out.println(collect);}//5.有没有交易员是在米兰工作的@Testpublic void test5() {boolean milan = transactions.stream().anyMatch((t) -> t.getTrader().getCity().equals("Milan"));System.out.println(milan);}//6.打印生活在剑桥的交易员的所有交易额@Testpublic void test6() {Integer cambridge = transactions.stream().filter((x) -> x.getTrader().getCity().equals("Cambridge")).map(Transaction::getValue).reduce(0, Integer::sum);System.out.println(cambridge);}//7.所有交易中,最高的交易额是多少@Testpublic void test7() {Optional<Integer> max = transactions.stream().map(Transaction::getValue).max(Integer::compare);System.out.println(max.get());}//8.找到交易额最小的交易@Testpublic void test8() {Optional<Transaction> min = transactions.stream().min((x, y) -> Integer.compare(x.getValue(), y.getValue()));System.out.println(min.get());}
四.并行流与串行流
1.并行流:
就是把一个内容分成几个数据块,并用不同的线程分别处理每个数据块的流。
Java 8 中将并行进行了优化,我们可以很容易的对数据进行操作;Stream API 可以声明性地通过 parallel() 与 sequential() 在并行流与串行流之间切换。2.了解Fork/Join框架
1.Fork/Join框架:
就是在必要的情况下,将一个大人物,进行拆分(fork)成若干个小任务(拆到不可再拆时),再将一个个的小任务运算的结果进行join汇总。
2.Fork/Join框架与传统线程池的区别:
采用“工作窃取”模式(work-stealing):
当执行新的任务时它可以将其拆分分成更小的任务执行,并将小人物加到线程队列中,然后再从一个随机线程的队列中偷一个并把它放在自己的队列中。
相对于一般的线程池实现,fork/join框架的优势体现在对其中包含的任务的处理方式上。在一般的线程池中,如果一个线程正在执行的任务由于某些原因无法继续运行,那么该线程会处于等待状态。而在fork/join框架实现中,如果某个子问题由于等待另外一个子问题的完成而无法继续运行。那么处理该子问题的线程会主动寻找其他尚未运行的子问题来执行。这种方式减少了线程的等待时间,提高了性能。
public class ForkJoinCalculate extends RecursiveTask<Long> {private static final long serialVersionUID = 1234567890L;private long start;private long end;private static final long THRESHOLD = 100000;public ForkJoinCalculate(long start, long end) {this.start = start;this.end = end;}@Overrideprotected Long compute() {long length = end - start;if (length <= THRESHOLD) {long sum = 0;for (long i = start; i <= end; i++) {sum += i;}return sum;} else {long middle = (start + end) / 2;ForkJoinCalculate left = new ForkJoinCalculate(start, middle);left.fork();//拆分子任务,同时压入线程队列ForkJoinCalculate right = new ForkJoinCalculate(middle + 1, end);right.fork();return left.join() + right.join();}}}
/*** ForkJoin框架*/@Testpublic void test1() {Instant start = Instant.now();ForkJoinPool pool = new ForkJoinPool();ForkJoinTask<Long> task = new ForkJoinCalculate(0, 100000000000L);Long sum = pool.invoke(task);System.out.println(sum);Instant end = Instant.now();System.out.println("完成时间:" + Duration.between(start, end).toMillis());}/*** 普通for循环*/@Testpublic void test2() {Instant start = Instant.now();long sum = 0L;for (long i = 0; i <= 100000000000L; i++) {sum += i;}System.out.println(sum);Instant end = Instant.now();System.out.println("完成时间:" + Duration.between(start, end).toMillis());}/*** java8并行流*串行流(单线程):切换为并行流 parallel()*并行流:切换为串行流 sequential()*/@Testpublic void test3() {Instant start = Instant.now();long reduce = LongStream.rangeClosed(0, 100000000000L).parallel()//底层:ForkJoin 并行执行.reduce(0, Long::sum);System.out.println(reduce);Instant end = Instant.now();System.out.println("完成时间:" + Duration.between(start, end).toMillis());}
