JDK8的集合流式操作

来源:互联网 发布:网络黑侠哪本作品好 编辑:程序博客网 时间:2024/05/29 13:38
一. 基本概念
1.1 为什么加入 集合的流式操作     
        JDK8 的Stream 是一个受到 函数式编程 和 多核时代影响而产生的东西。很多时候我们需要到底层返回数据,上层再对数据进行遍历,进行一些数据统计,但是之前的Java API 中很少有这种方法,这就需要我们自己来 Iterator 来遍历,如果JDK 能够为我们提供一些这种方法,并且能够为我们优化就好了。
         所以JDK8加入 了 java.util.stream包,实现了集合的流式操作,流式操作包括集合的过滤,排序,映射等功能。根据流的操作性,又可以分为 串行流 和 并行流。根据操作返回的结果不同,流式操作又分为中间操作和最终操作。大大方便了我们对于集合的操作。
  • 最终操作:返回一特定类型的结果。
  • 中间操作:返回流本身。
1.2 什么是 流
        Stream 不是 集合元素,也不是数据结构,它相当于一个 高级版本的 Iterator,不可以重复遍历里面的数据,像水一样,流过了就一去不复返。它和普通的 Iterator 不同的是,它可以并行遍历,普通的 Iterator 只能是串行,在一个线程中执行。

二. 串行流和并行流:
        串行流操作在一个线程中依次完成。并行流在多个线程中完成,主要利用了 JDK7 的 Fork/Join 框架来拆分任务和加速处理。相比串行流,并行流可以很大程度提高程序的效率。

三. 中间操作 和 最终操作        
中间操作:
  • filter(): 对元素进行过滤
  • sorted():对元素排序
  • map():元素映射
  • distinct():去除重复的元素
最终操作:
  • forEach():遍历每个元素。
  • reduce():把Stream 元素组合起来。例如,字符串拼接,数值的 sum,min,max ,average 都是特殊的 reduce。
  • collect():返回一个新的集合。
  • min():找到最小值。
  • max():找到最大值。

3.1 filter() 对元素进行过滤
Demo(有一链表,{1,2,3,4,5},把偶数过滤掉):
[java] view plain copy
  1. public class Test {  
  2.     public static void main(String[] args) throws InterruptedException {  
  3.         List list = new ArrayList();  
  4.         for(int i = 1 ; i <= 5; ++i){  
  5.             list.add(i);  
  6.         }  
  7.         list.stream().filter(param -> (int)param % 2 == 1)  
  8.                     .forEach(System.out::println);  
  9.     }  
  10. }  
输出:
[plain] view plain copy
  1. 1  
  2. 3  
  3. 5  

3.2 sorted() 对元素进行排序
Demo(有一链表,{2,3,1,5,4},从小到大排序):
[java] view plain copy
  1. public class Test {  
  2.     public static void main(String[] args) throws InterruptedException {  
  3.         List list = new ArrayList();  
  4.         list.add(2);  
  5.         list.add(3);  
  6.         list.add(1);  
  7.         list.add(5);  
  8.         list.add(4);  
  9.         list.stream().sorted().forEach(System.out::println);  
  10.     }  
  11. }  
输出:
[plain] view plain copy
  1. 1  
  2. 2  
  3. 3  
  4. 4  
  5. 5  
Ps1: 此时为升序,那么有时候我们可能会需要到降序,此时做法可以如下:
        流除了提供默认的升序 sorted() 方法,也提供了:    
[java] view plain copy
  1. Stream<T> sorted(Comparator<? super T> comparator);  
        那么,自定义比较函数即可,如下代码:
[java] view plain copy
  1. public class Test {  
  2.     public static void main(String[] args) throws InterruptedException {  
  3.         List list = new ArrayList();  
  4.         list.add(2);  
  5.         list.add(3);  
  6.         list.add(1);  
  7.         list.add(5);  
  8.         list.add(4);  
  9. //      list.stream().sorted().forEach(System.out::println);  
  10.         list.stream().sorted( (param1,param2) -> ((int)param1 < (int)param2 ? 1 : -1 ) )  
  11.                 .forEach(System.out::println);  
  12.     }  
  13. }  
输出为:
[plain] view plain copy
  1. 5  
  2. 4  
  3. 3  
  4. 2  
  5. 1  
3.3 map() 元素映射
        也就是说,原来的链表的每个元素可以按照规则变成相应的元素。
Demo(链表 (1,0),变成 true,false):
[java] view plain copy
  1. public class Test {  
  2.     public static void main(String[] args) throws InterruptedException {  
  3.         List list = new ArrayList();  
  4.         list.add(1);  
  5.         list.add(0);  
  6.         list.stream().map( param -> (int)param == 1 ? true:false )  
  7.                 .forEach(System.out::println);  
  8.     }  
  9. }  
输出:
[plain] view plain copy
  1. true  
  2. false  
3.4  distinct() 去除重复元素
Demo:
[java] view plain copy
  1. public class Test {  
  2.     public static void main(String[] args) throws InterruptedException {  
  3.         List list = new ArrayList();  
  4.         list.add(1);  
  5.         list.add(1);  
  6.         list.add(0);  
  7.         list.stream().distinct().forEach(System.out::println);  
  8.     }  
  9. }  
3.5 reduce() :把Stream 元素组合起来。
Demo(从1加到5):
[java] view plain copy
  1. public class Test {  
  2.     public static void main(String[] args) throws InterruptedException {  
  3.         List list = new ArrayList();  
  4.         list.add(1);  
  5.         list.add(2);  
  6.         list.add(3);  
  7.         list.add(4);  
  8.         list.add(5);  
  9.         System.out.println(  
  10.                 list.stream().reduce((param1,param2) ->(int)param1 + (int)param2 ).get());  
  11.     }  
  12. }  
        注意,reduce() 返回一个 Optional 类型的对象,可以通过 get() 方法获得值。

3.6 collect() :返回一个新的集合
Demo(先把 list 集合的 奇数去掉,然后把剩下的偶数返回到 _list 集合中):
[java] view plain copy
  1. public class Test {  
  2.     public static void main(String[] args) throws InterruptedException {  
  3.         List list = new ArrayList();  
  4.         list.add(1);  
  5.         list.add(2);  
  6.         list.add(3);  
  7.         list.add(4);  
  8.         list.add(5);  
  9.           
  10.         List _list = (List) list.stream().filter((param) -> (int)param % 2 == 0)  
  11.                         .collect(Collectors.toList());  
  12.         _list.forEach(System.out::println);  
  13.     }  
  14. }  
输出:
[plain] view plain copy
  1. 2  
  2. 4  
3.7 min(),max()  找到最大值最小值
[java] view plain copy
  1. public class Test {  
  2.     public static void main(String[] args) throws InterruptedException {  
  3.         List list = new ArrayList();  
  4.         list.add(1);  
  5.         list.add(2);  
  6.         list.add(3);  
  7.         list.add(4);  
  8.         list.add(5);  
  9.           
  10.         System.out.println(list.stream().min(  
  11.                 (param1,param2) -> (int)param1 > (int)param2 ? 1:-1 ).get());  
  12.         System.out.println(list.stream().max(  
  13.                 (param1,param2) -> (int)param1 > (int)param2 ? 1:-1 ).get());  
  14.     }  
  15. }  
        注意, min(),max() 方法也是返回 Optional 对象, 可以通过 get() 方法返回值。
        
总结:
1. 流式操作的引入:提高执行效率(并行),方便编码(有很多API 可用),提高可读性。
2. 流的分类:可以分为串行流和并行流;对于操作:可以分为中间操作和最终操作
3. 流API:
        中间操作:
                filter(): 对元素进行过滤;
                sorted():对元素排序;
                map():元素映射;
                distinct():去除重复的元素 。
        最终操作:
                forEach():遍历每个元素;
                reduce():把Stream 元素组合起来。例如,字符串拼接,数值的 sum,min,max ,average 都是特殊的 reduce。
                collect():返回一个新的集合。
                min():找到最小值。
                max():找到最大值。
0 0
原创粉丝点击