Java StreamAPI 详解

Java8中有两大最为重要的改变。第一个是 Lambda 表达式;另外一个则是 Stream API(java.util.stream.*)。Stream 是 Java8 中处理集合的关键抽象概念,它可以指定对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。简而言之,Stream API 提供了一种高效且易于使用的处理数据的方式

流(Stream)是数据渠道,用于操作数据源 (集合、数组等) 所生成的元素序列

集合讲的是数据,流讲的是计算

注 : 1> Stream 自己不会存储元素
       2> Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream
       3> Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行

Stream 的操作三个步骤
1> 创建 Stream : 一个数据源 (如 : 集合、数组), 获取一个流
2> 中间操作 : 一个中间操作链,对数据源的数据进行处理
3> 终止操作(终端操作) : 一个终止操作,执行中间操作链,并产生结果



创建 Stream
Java8 中的 Collection 接口被扩展,提供两个获取流的方法 :
default Stream<E> stream() : 返回一个顺序流
default Stream<E> parallelStream() : 返回一个并行流

// Collection 提供了两个方法  stream() 与 parallelStream()
List<String> list =  new  ArrayList<>();
Stream<String> stream = list.stream();  // 获取一个顺序流
Stream<String> parallelStream = list.parallelStream();  // 获取一个并行流

由数组创建流
Java8 中的 Arrays 的静态方法 stream() 可以获取数组流 :
static <T> Stream<T> stream(T[] array) : 返回一个流
重载形式,能够处理对应基本类型的数组 :
public static IntStream stream(int[] array)
public static LongStream stream(long[] array)
public static DoubleStream stream(double[] array)

// 通过 Arrays 中的 stream() 获取一个数组流
Stream<Integer> stream1 = Arrays. stream ( new  Integer[ 10 ]);

由值创建流
可以使用静态方法 Stream.of(), 通过显示值创建一个流,它可以接收任意数量的参数
public static<T> Stream<T> of(T... values) : 返回一个流

// 通过 Stream 类中静态方法 of()
Stream<Integer> stream2 = Stream. of ( 1 ,  2 ,  3 ,  4 ,  5 ,  6 );
注 : Stream.of静态方法 底层就是 Arrays.stream 静态方法

由函数创建流 : 创建无限流
可以使用静态方法 Stream.iterate() 和 Stream.generate(), 创建无限流
迭代
public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
生成
public static<T> Stream<T> generate(Supplier<T> s)

// 创建无限流
// 迭代
Stream<Integer> stream3 = Stream. iterate ( 0 , (x) -> x +  2 ).limit( 10 );
stream3.forEach(System. out ::println);

// 生成
Stream<Double> stream4 = Stream. generate (Math:: random ).limit( 2 );
stream4.forEach(System. out ::println);


Stream 的中间操作
多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理。而在终止操作时一次性全部处理,称为“惰性求值”

筛选与切片
方 法
描 述
filter(Predicate p)
接收 Lambda , 从流中排除某些元素
distinct()
筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
limit(long maxSize)
截断流,使其元素不超过给定数量
skip(long n)
跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
// 内部迭代 : 迭代操作 Stream API 内部完成
// 所有的中间操作不会做任何的处理
Stream<Employee> stream =  emps .stream().filter((e) -> e.getAge() <=  35 );
// 只有当做终止操作时,所有的中间操作会一次性的全部执行,称为“惰性求值”
stream.forEach(System. out ::println);

// 外部迭代
Iterator<Employee> it =  emps .iterator();
while  (it.hasNext()) {
    System. out .println(it.next());
}
emps .stream().filter(e -> e.getSalary() >=  5000 ).limit( 3 ).forEach(System. out ::println);
emps .parallelStream().filter((e) -> e.getSalary() >=  5000 ).skip( 2 ).forEach(System. out ::println);
emps .stream().distinct().forEach(System. out ::println);

映射
方 法
描 述
map(Function f)
接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
mapToDouble(ToDoubleFunction f)
接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 DoubleStream
mapToInt(ToIntFunction f)
接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 IntStream
mapToLong(ToLongFunction f)
接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 LongStream
flatMap(Function f)
接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
Stream<String> str =  emps .stream().map(Employee::getName);

List<String> strList = Arrays. asList ( "aaa""bbb""ccc""ddd""eee" );
Stream<String> stream1 = strList.stream().map(String::toUpperCase);
stream1.forEach(System. out ::println);

public static  Stream<Character> filterCharacter(String str) {
    List<Character> list =  new  ArrayList<>();
     for  (Character ch : str.toCharArray()) {
        list.add(ch);
    }
     return  list.stream();
}

Stream<Stream<Character>> stream2 = strList.stream().map(TestStreamaAPI2:: filterCharacter );
stream2.forEach(sm -> sm.forEach(System. out ::println));

Stream<Character> stream3 = strList.stream().flatMap(TestStreamaAPI2:: filterCharacter );
stream3.forEach(System. out ::println);

给定一个数字列表,如何返回一个由每个数的平方构成的列表呢?(给定[1,2,3,4,5], 应该返回[1,4,9,16,25])
Integer[] nums =  new  Integer[]{ 1 ,  2 ,  3 ,  4 ,  5 };
Arrays. stream (nums).map((x) -> x * x).forEach(System. out ::println);

排序

方 法
描 述
sorted()
产生一个新流,其中按自然顺序排序
sorted(Comparator comp)
产生一个新流,其中按比较器顺序排序
emps .stream().map(Employee::getName).sorted().forEach(System. out ::println);
emps .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);


Stream 的终止操作
终端操作会从流的流水线生成结果,其结果可以是任何不是流的值,例如 : List、 Integer,甚至是 void

查找与匹配
方 法
描 述
allMatch(Predicate p)
检查是否匹配所有元素
anyMatch(Predicate p)
检查是否至少匹配一个元素
noneMatch(Predicate p)
检查是否没有匹配所有元素
findFirst()
返回第一个元素
findAny()
返回当前流中的任意元素
count()
返回流中元素总数
max(Comparator c)
返回流中最大值
min(Comparator c)
返回流中最小值
forEach(Consumer c)
内部迭代(使用 Collection 接口需要用户去做迭代,称为外部迭代。相反, Stream API 使用内部迭代)
boolean  bl =  emps .stream().allMatch(e -> e.getStatus().equals(Status. BUSY ));
System. out .println(bl);

boolean  bl1 =  emps .stream().anyMatch(e -> e.getStatus().equals(Status. BUSY ));
System. out .println(bl1);

boolean  bl2 =  emps .stream().noneMatch(e -> e.getStatus().equals(Status. BUSY ));
System. out .println(bl2);

Optional<Employee> op1 =  emps .stream().sorted((e1, e2) -> Double. compare (e1.getSalary(), e2.getSalary())).findFirst();
System. out .println(op1.get());

Optional<Employee> op2 =  emps .parallelStream().filter((e) -> e.getStatus().equals(Status. FREE )).findAny();
System. out .println(op2.get());

long  count =  emps .stream().filter((e) -> e.getStatus().equals(Status. FREE )).count();
System. out .println(count);

Optional<Double> op =  emps .stream().map(Employee::getSalary).max(Double:: compare );
System. out .println(op.get());

Optional<Employee> op2 =  emps .stream().min((e1, e2) -> Double. compare (e1.getSalary(), e2.getSalary()));
System. out .println(op2.get());

注 : 流进行了终止操作后,不能再次使用
Stream<Employee> stream =  emps .stream().filter(e -> e.getStatus().equals(Status. FREE ));
long  count = stream.count();
System. out .println(count);

stream.map(Employee::getSalary).max(Double:: compare );


归约
方 法
描 述
reduce(T iden, BinaryOperator b)
可以将流中元素反复结合起来,得到一个值,返回 T
reduce(BinaryOperator b)
可以将流中元素反复结合起来,得到一个值,返回 Optional<T>
注 : map 和 reduce 的连接通常称为 map-reduce 模式,因 Google 用它来进行网络搜索而出名
List<Integer> list = Arrays. asList ( 1 ,  2 ,  3 ,  4 ,  5 ,  6 ,  7 ,  8 ,  9 ,  10 );
Integer sum = list.stream().reduce( 0 , (x, y) -> x + y);
System. out .println(sum);

Optional<Double> op =  emps .stream().map(Employee::getSalary).reduce(Double:: sum );
System. out .println(op.get());

需求 : 搜索名字中 “六” 出现的次数
Optional<Integer> sum =  emps .stream()
        .map(Employee::getName)
        .flatMap(TestStreamaAPI2:: filterCharacter )
        .map((ch) -> {
             if  (ch.equals( '六' )) {
                 return  1 ;
            }  else  {
                 return  0 ;
            }
        }).reduce(Integer:: sum );
System. out .println(sum.get());

收集
方 法
描 述
collect(Collector c)
将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
Collector 接口中方法的实现决定如何对流执行收集操作(如收集到 List、 Set、 Map),但是 Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例, 具体方法与实例如下表 :
 方法 返回类型 作用
 toList List<T> 把流中元素收集到List
 List<Employee> emps = list.stream().collect(Collectors.toList());
 toSet Set<T> 把流中元素收集到Set
 Set<Employee> emps = list.stream().collect(Collectors.toSet());
 toCollection Collection<T> 把流中元素收集到创建的集合
 Collection<Employee> emps = list.stream().collect(Collectors.toCollection(ArrayList::new));
counting Long 计算流中元素的个数
 long count = list.stream().collect(Collectors.counting());
 summingInt Integer 对流中元素的整数属性求和
 int total = list.stream().collect(Collectors.summingInt(Employee::getSalary));
 averagingInt Double 计算流中元素Integer属性的平均值
 double avg = list.stream().collect(Collectors.averagingInt(Employee::getSalary));
 summarizingInt IntSummaryStatistics 收集流中Integer属性的统计值,如 : 平均值
Int SummaryStatisticsiss = list.stream().collect(Collectors.summarizingInt(Employee::getSalary));
 joining String 连接流中每个字符串
String str = list.stream().map(Employee::getName).collect(Collectors.joining());
 maxBy Optional<T> 根据比较器选择最大值
Optional<Emp> max = list.stream().collect(Collectors.maxBy(comparingInt(Employee::getSalary)));
 minBy Optional<T> 根据比较器选择最小值
Optional<Emp> min = list.stream().collect(Collectors.minBy(comparingInt(Employee::getSalary)));
 reducing 归约产生的类型 从一个作为累加器的初始值开始,利用BinaryOperator与流中元素逐个结合,从而归约成单个值
int total = list.stream().collect(Collectors.reducing(0, Employee::getSalar, Integer::sum));
 collectingAndThen 转换函数返回的类型 包裹另一个收集器,对其结果转换函数
int how = list.stream().collect(Collectors.collectingAndThen(Collectors.toList(), List::size));
 groupingBy Map<K, List<T>> 根据某属性值对流分组,属性为K,结果为V
 Map<Emp.Status, List<Emp>> map =  list.stream().collect(Collectors.groupingBy(Employee::getStatus));
 partitioningBy Map<Boolean, List<T>> 根据true或false进行分区
 Map<Boolean,List<Emp>>vd= list.stream().collect(Collectors.partitioningBy(Employee::getManage));
List<String> list =  emps .stream().map(Employee::getName).collect(Collectors. toList ());
list.forEach(System. out ::println);

Set<String> set =  emps .stream().map(Employee::getName).collect(Collectors. toSet ());
set.forEach(System. out ::println);

HashSet<String> hs =  emps .stream().map(Employee::getName).collect(Collectors. toCollection (HashSet:: new ));
hs.forEach(System. out ::println);

Optional<Double> max =  emps .stream().map(Employee::getSalary).collect(Collectors. maxBy (Double:: compare ));
System. out .println(max.get());

Optional<Employee> op =  emps .stream().collect(Collectors. minBy ((e1, e2) -> Double. compare (e1.getSalary(), e2.getSalary())));
System. out .println(op.get());

Double sum =  emps .stream().collect(Collectors. summingDouble (Employee::getSalary));
System. out .println(sum);

Double avg =  emps .stream().collect(Collectors. averagingDouble (Employee::getSalary));
System. out .println(avg);

Long count =  emps .stream().collect(Collectors. counting ());
System. out .println(count);

DoubleSummaryStatistics dss =  emps .stream().collect(Collectors. summarizingDouble (Employee::getSalary));
System. out .println(dss.getMax());

// 分组

Map<Status, List<Employee>> map =  emps .stream().collect(Collectors. groupingBy (Employee::getStatus));
System. out .println(map);

// 多级分组
Map<Status, Map<String, List<Employee>>> map =  emps .stream()
        .collect(Collectors. groupingBy (Employee::getStatus, Collectors. groupingBy ((e) -> {
             if  (e.getAge() >=  60 ) {
                 return  "老年" ;
            }  else if  (e.getAge() >=  35 ) {
                 return  "中年" ;
            }  else  {
                 return  "成年" ;
            }
        })));
System. out .println(map);

String str =  emps .stream().map(Employee::getName)
        .collect(Collectors. joining ( "," ,  "----" ,  "----" ));
System. out .println(str);
Optional<Double> sum =  emps .stream().map(Employee::getSalary).collect(Collectors. reducing (Double:: sum ));
System. out .println(sum.get());

实例 :
交易员类
public class  Trader {
     private  String  name ;
     private  String  city ;
     public  Trader() {
    }
     // ...
     @Override
     public  String toString() {
         return  "Trader [name="  +  name  +  ", city="  +  city  +  "]" ;
    }
}

交易类
public class  Transaction {
     private  Trader  trader ;
     private int  year ;
     private int  value ;
     public  Transaction() {
    }
     public  Transaction(Trader trader,  int  year,  int  value) {
         this . trader  = trader;
         this . year  = year;
         this . value  = value;
    }
    // ...
     @Override
     public  String toString() {
         return  "Transaction [trader="  +  trader  +  ", year="  +  year  +  ", value="  +  value  +  "]" ;
    }
}

初始化数据
List<Transaction>  transactions  =  null ;

@Before
public 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年发生的所有交易, 并按交易额排序(从低到高)
transactions .stream().filter((t) -> t.getYear() ==  2011 ) .sorted((t1, t2) -> Integer. compare (t1.getValue(), t2.getValue())).forEach(System. out ::println);

2. 交易员都在哪些不同的城市工作过
transactions .stream().map((t) -> t.getTrader().getCity()).distinct().forEach(System. out ::println);

3. 查找所有来自剑桥的交易员,并按姓名排序
transactions .stream().filter((t) -> t.getTrader().getCity().equals( "Cambridge" )).map(Transaction::getTrader)
        .sorted(Comparator. comparing (Trader::getName)).distinct().forEach(System. out ::println);

4. 返回所有交易员的姓名字符串,按字母顺序排序
transactions .stream().map((t) -> t.getTrader().getName()).sorted().forEach(System. out ::println);

String str =  transactions .stream().map((t) -> t.getTrader().getName()).sorted().reduce( "" , String::concat);
System. out .println(str);

public static  Stream<String> filterCharacter(String str) {
    List<String> list =  new  ArrayList<>();
     for  (Character ch : str.toCharArray()) {
        list.add(ch.toString());
    }
     return  list.stream();
}
transactions .stream().map((t) -> t.getTrader().getName()).flatMap(TestTransaction:: filterCharacter ).sorted(String::compareToIgnoreCase).forEach(System. out ::print);

5. 有没有交易员是在米兰工作的
boolean  bl =  transactions .stream().anyMatch((t) -> t.getTrader().getCity().equals( "Milan" ));
System. out .println(bl);

6. 打印生活在剑桥的交易员的所有交易额
Optional<Integer> sum =  transactions .stream().filter((e) -> e.getTrader().getCity().equals( "Cambridge" ))
        .map(Transaction::getValue).reduce(Integer:: sum );
System. out .println(sum.get());

7. 所有交易中,最高的交易额是多少
Optional<Integer> max =  transactions .stream().map(Transaction::getValue).max(Integer:: compare );
System. out .println(max.get());

8. 找到交易额最小的交易
Optional<Transaction> op =  transactions .stream().min((t1, t2) -> Integer. compare (t1.getValue(), t2.getValue()));
System. out .println(op.get());

并行流与串行流
并行流就是把一个内容分成多个数据块,并用不同的线程分别处理每个数据块的流。Java 8 中将并行进行了优化,可以很容易的对数据进行并行操作。 Stream API 可以声明性地通过 parallel() 与 sequential() 在并行流与顺序流之间进行切换

Fork/Join 框架
Fork/Join 框架 : 就是在必要的情况下,将一个大任务,进行拆分(fork)成若干个小任务 (拆到不可再拆时),再将一个个的小任务运算的结果进行 join 汇总


Fork/Join 框架与传统线程池的区别
采用 “工作窃取”模式 (work-stealing)  : 当执行新的任务时它可以将其拆分分成更小的任务执行,并将小任务加到线程队列中,然后再从一个随机线程的队列中偷一个并把它放在自己的队列中
相对于一般的线程池实现,fork/join框架的优势体现在对其中包含的任务的处理方式上。在一般的线程池中,如果一个线程正在执行的任务由于某些原因无法继续运行,那么该线程会处于等待状态。而在fork/join框架实现中,如果某个子问题由于等待另外一个子问题的完成而无法继续运行。那么处理该子问题的线程会主动寻找其他尚未运行的子问题来执行。或者当线程任务完成速度快,就会随机抽取其它未完成任务的进程中的最后一个任务进行计算操作。这种方式减少了线程的等待时间,提高了性能

普通 for(最慢,数据量越大CPU使用率低,速度越慢)
long  start = System. currentTimeMillis ();

long  sum =  0L ;
for  ( long  i =  0L ; i <=  10000000000L ; i++) {
    sum += i;
}
System. out .println(sum);

long  end = System. currentTimeMillis ();
System. out .println( "耗费的时间为: "  + (end - start));  //34-3174-3132-4227-4223-31583

ForkJoin框架(比较快)
public class  ForkJoinCalculate  extends  RecursiveTask<Long> {
     private static final long  serialVersionUID  =  13475679780L ;
     private long  start ;
     private long  end ;
     private static final long  THRESHOLD  =  10000L ;  //临界值
     public  ForkJoinCalculate( long  start,  long  end) {
         this . start  = start;
         this . end  = end;
    }
     @Override
     protected  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();
        }
    }
}

long  start = System. currentTimeMillis ();

ForkJoinPool pool =  new  ForkJoinPool();
ForkJoinTask<Long> task =  new  ForkJoinCalculate( 0L ,  10000000000L );

long  sum = pool.invoke(task);
System. out .println(sum);

long  end = System. currentTimeMillis ();
System. out .println( "耗费的时间为: "  + (end - start));  //112-1953-1988-2654-2647-20663-113808

Java8 并行流(底层使用ForkJoin框架,速度最快 CPU使用率可以达到 100%)
long  start = System. currentTimeMillis ();

Long sum = LongStream. rangeClosed ( 0L ,  10000000000L ).parallel().sum();
System. out .println(sum);

long  end = System. currentTimeMillis ();
System. out .println( "耗费的时间为: "  + (end - start));  //2061-2053-2086-18926

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值