jdk8函数编程

jdk8函数编程

Stream1
流的操作分为两类
1. Intermediate (map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered) 仅仅是对流数据过滤或映射 (流过)
2. Terminal (forEach、 forEachOrdered、 toArray、 reduce、 collect、 min、 max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 iterator) 终结流(到这儿终止不返回新的流,当它执行时才会真正开始遍历)
3. Short-circuiting (anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 limit) 当操作无限大的流,需要这些返回一个有限的流

1. reduce

Streamone=Stream.of("one","two","three","four");
//将流内的值组合起来sum.max都是特殊的reduce
Optionalreduce=one.reduce((s,s2)->s+s2);
booleanb=one.allMatch(s->s.length()>3);

  1. Listcollect1=Stream.of("one","two","three","four")
    .filter(e->e.length()>3)
    .peek(e->System.out.println("Filteredvalue:"+e))
    .map(String::toUpperCase)
    .sorted()
    .collect(Collectors.toList());

    1. Flatmap 合并多个流
      Stream<List>inputStream=Stream.of(
      Arrays.asList(1),
      Arrays.asList(2,3),
      Arrays.asList(4,5,6)
      );

StreamoutputStream=inputStream.flatMap((childList)->childList.stream());

4. Collect

Stream.collect(ArrayList::new, ArrayList::add);
Stream.collect(Collectors.toMap(Functions.identity, item -> item+ "aa"));

Stream操作分类
中间操作(Intermediate operations) 无状态(Stateless) unordered() filter() map() mapToInt() mapToLong() mapToDouble() flatMap() flatMapToInt() flatMapToLong() flatMapToDouble() peek()
有状态(Stateful) distinct() sorted() sorted() limit() skip()
结束操作(Terminal operations) 非短路操作 forEach() forEachOrdered() toArray() reduce() collect() max() min() count()
短路操作(short-circuiting) anyMatch() allMatch() noneMatch() findFirst() findAny()

Stream上的所有操作分为两类:中间操作和结束操作,中间操作只是一种标记,只有结束操作才会触发实际计算。中间操作又可以分为无状态的(Stateless)和有状态的(Stateful),无状态中间操作是指元素的处理不受前面元素的影响,而有状态的中间操作必须等到所有元素处理之后才知道最终结果,比如排序是有状态操作,在读取所有元素之前并不能确定排序结果;结束操作又可以分为短路操作和非短路操作,短路操作是指不用处理全部元素就可以返回结果,比如找到第一个满足条件的元素。之所以要进行如此精细的划分,是因为底层对每一种情况的处理方式不同。

Complefuture

/supplyAsync需要异步处理的结果()->{}
thenApply对结果进行再次加工
thenCompose调用别的处理结果,组装
join等待结果
thenCombine调用别的处理结果,组装
exceptionally出现异常进行
/

//complefuture进行组合
shops.stream()
.map(shop->CompletableFuture.supplyAsync(()->shop.getPrice(product),executor))
.map(future->future.thenApply((shop)->shop.getName()+"aaa"))
.map(future->future.thenCompose(quote->CompletableFuture.supplyAsync((quote2)->"quote="+quote2,executor)));

Optional

Optional.ofNullable("aa").ifPresent(System.out::println);

Integerlength=Optional.ofNullable("aa").map(String::length).orElse(-1);

FunctionInterface
1. Consumer andThen 按顺序执行
2. Function 转换类型 compose 先执行后面的 andThen顺序执行
3. Predicate test and 组装条件
4. Supplier get

Lamda 不是匿名内部类的简写

new Thread(() -> System.out.println("")).start();

Javap -c -p 后

 public static void main(java.lang.String[]);
    Code:
       0: new           #2                  // class java/lang/Thread
       3: dup
       4: invokedynamic #3,  0              // InvokeDynamic #0:run:()Ljava/lang/Runnable;
       9: invokespecial #4                  // Method java/lang/Thread."<init>":(Ljava/lang/Runnable;)V
      12: invokevirtual #5                  // Method java/lang/Thread.start:()V
      15: return
 
  private static void lambda$main$0();
    Code:
       0: getstatic     #6                  // Field java/lang/System.out:Ljava/io/PrintStream;
       3: ldc           #7                  // String
       5: invokevirtual #8                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       8: return

反编译后发现是封装为主类的私有方法通过invokedynamic调用 invokedynamic的介绍
同理 在lamda中的this 与外部一样, 而匿名内部类则是自己创建的对象

Thread s = new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println(this);
    }
});

posted @ 2022-10-11 22:43  jojoworld  阅读(61)  评论(0编辑  收藏  举报