//异步线程
CompletableFuture.runAsync(()->{
businessInternalService.createAccount(contractId);
});

//无返回值
CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
System.out.println("runAsync无返回值");
});

future1.get();

//有返回值
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("supplyAsync有返回值");
return "111";
});

String s = future2.get();

// 输出:hello System.out.println(Optional.ofNullable(hello).orElse("hei"));

// 输出:hei System.out.println(Optional.ofNullable(null).orElse("hei"));

// 输出:hei System.out.println(Optional.ofNullable(null).orElseGet(() -> "hei"));

// 输出:RuntimeException: eeeee... System.out.println(Optional.ofNullable(null).orElseThrow(() -> new RuntimeException("eeeee...")));

操作类型

  • Intermediate:

map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered

  • Terminal:

forEach、 forEachOrdered、 toArray、 reduce、 collect、 min、 max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 iterator

  • Short-circuiting:

anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 limit

  • Optional.of(T),T为非空,否则初始化报错
  • Optional.ofNullable(T),T为任意,可以为空
  • isPresent(),相当于 !=null
  • ifPresent(T), T可以是一段lambda表达式 ,或者其他代码,非空则执行
List<Integer> list = Arrays.asList(10, 20, 30, 10);
//通过reduce方法得到一个Optional类
int a = list.stream().reduce(Integer::sum).orElse(get("a"));
int b = list.stream().reduce(Integer::sum).orElseGet(() -> get("b"));
System.out.println("a "+a);
System.out.println("b "+b);
System.out.println("hello world");
//去重复
List<Integer> userIds = new ArrayList<>();
List<OldUserConsumeDTO> returnResult = result.stream().filter(
v -> {
boolean flag = !userIds.contains(v.getUserId());
userIds.add(v.getUserId());
return flag;
}
).collect(Collectors.toList());
orElseThrow
//        MyDetailDTO model= Optional.ofNullable(feignUserServiceClient.getUserID(loginUserId)).map((x)->{
// return s;
// }).orElseThrow(()->new RuntimeException("用户不存在"));
ifPresent
 Optional.ofNullable(relCDLSuccessTempates.getTemplate()).ifPresent(template -> {
// cdlSuccessTemplateDetailDTO.setTemplateId(template.getId());
// cdlSuccessTemplateDetailDTO.setTitle(template.getTitle());
// cdlSuccessTemplateDetailDTO.setDescription(template.getDescription());
// cdlSuccessTemplateDetailDTO.setKeywords(template.getKeywords());
// });
distinct

 List<Integer>  result=  list.stream().distinct().collect(Collectors.toList());
 
averagingInt
int integer=  list.stream().collect(Collectors.averagingInt());

Optional< String > fullName = Optional.ofNullable( null );
System.out.println( "Full Name is set? " + fullName.isPresent() );
System.out.println( "Full Name: " + fullName.orElseGet( () -> "[none]" ) );
System.out.println( fullName.map( s -> "Hey " + s + "!" ).orElse( "Hey Stranger!" ) );
 final long totalPointsOfOpenTasks = list
// .stream()
// //.filter( task -> task.getStatus() == Status.OPEN )
// .mapToInt(x->x)
// .sum();
list.stream().collect(Collectors.groupingBy((x)->x));

Map&groupingBy
  Map<Integer, MyDetailDTO> collect = result.stream().collect(Collectors.toMap(MyDetailDTO::getTeamsNumber, u -> u));
Map<Integer,List<MyDetailDTO>> map = result.stream().collect(Collectors.groupingBy(MyDetailDTO::getTeamsNumber));
parallelStream
long begin = System.currentTimeMillis();
//        List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
// // 获取空字符串的数量
// int count = (int) strings.parallelStream().filter(string -> string.isEmpty()).count();
// System.out.println("schedulerTaskCityMaster耗时:" + (System.currentTimeMillis() - begin));

joining
String mergedString = list.stream().collect(Collectors.joining(", "));

comparing&thenComparing
 result.sort(Comparator.comparing(MyDetailDTO::getStraightPushNumber)
// .thenComparing(MyDetailDTO::getTeamsNumber)
// .thenComparing(MyDetailDTO::getTeamsNumber));
flatMap
//转换之前 public String getCarInsuranceName(Person person) { return person.getCar().getInsurance().getName(); }
 
 
//转换后 public String getCarInsuranceName(Optional<Person> person) { return person.flatMap(Person::getCar) .flatMap(Car::Insurance) .map(Insurance::getName) .orElse("Unknown"); }

min
Optional<User> min = list.stream().min(Comparator.comparing(User::getUserId));
 
 Collectors.toMap
Map<Integer, User> collect = list.stream().collect(Collectors.toMap(User::getUserId, u -> u));
for (Integer in : collect.keySet())
{ User u = collect.get(in);//得到每个key多对用value的值 println(u); }
 
 
Stream.of(1, 2, 3)
.flatMap(integer -> Stream.of(integer * 10))
.forEach(System.out::println);
 
 //返回类型不一样
List<String> collect = data.stream()
.flatMap(person -> Arrays.stream(person.getName().split(" "))).collect(toList()); List<Stream<String>> collect1 = data.stream()
.map(person -> Arrays.stream(person.getName().split(" "))).collect(toList()); //用map实现
List<String> collect2 = data.stream()
.map(person -> person.getName().split(" "))
.flatMap(Arrays::stream).collect(toList());
//另一种方式
List<String> collect3 = data.stream()
.map(person -> person.getName().split(" "))
.flatMap(str -> Arrays.asList(str).stream()).collect(toList());
 
 anyMatch&noneMatch&allMatch
boolean anyMatch = list.stream().anyMatch(u -> u.getAge() == 100);
boolean allMatch = list.stream().allMatch(u -> u.getUserId() == 10);
boolean noneMatch = list.stream().noneMatch(u -> u.getUserId() == 10);
 
 sum&max&min
Optional<Integer> sum = list.stream().map(User::getAge).reduce(Integer::sum);
Optional<Integer> max = list.stream().map(User::getAge).reduce(Integer::max);
Optional<Integer> min = list.stream().map(User::getAge).reduce(Integer::min);
  //同步
long start1=System.currentTimeMillis();
list.stream().collect(Collectors.toSet());
System.out.println(System.currentTimeMillis()-start1); //并发
long start2=System.currentTimeMillis();
list.parallelStream().collect(Collectors.toSet());
System.out.println(System.currentTimeMillis()-start2);

personList.stream().sorted(Comparator.comparing((Person::getAge).thenComparing(Person::getId())).collect(Collectors.toList()) //先按年龄从小到大排序,年龄相同再按id从小到大排序

List<Integer> list = Arrays.asList(10, 20, 30, 40);
List<Integer> result1= list.stream().sorted(Comparator.comparingInt((x)->(int)x).reversed()).collect(Collectors.toList());
System.out.println(result1);


https://segmentfault.com/a/1190000018768907

Java8stream表达式的更多相关文章

  1. Java 8 新特性之 Lambda表达式

    Lambda的出现就是为了增强Java面向过程编程的深度和灵活性.今天就来分享一下在Java中经常使用到的几个示例,通过对比分析,效果应该会更好. – 1.实现Runnable线程案例 其存在的意义就 ...

  2. java8-Stream集合操作快速上手

    java8-Stream集合操作快速上手   目录 Stream简介 为什么要使用Stream 实例数据源 Filter Map FlatMap Reduce Collect Optional 并发 ...

  3. 【.net 深呼吸】细说CodeDom(2):表达式、语句

    在上一篇文章中,老周厚着脸皮给大伙介绍了代码文档的基本结构,以及一些代码对象与CodeDom类型的对应关系. 在评论中老周看到有朋友提到了 Emit,那老周就顺便提一下.严格上说,Emit并不是针对代 ...

  4. 你知道C#中的Lambda表达式的演化过程吗?

    那得从很久很久以前说起了,记得那个时候... 懵懂的记得从前有个叫委托的东西是那么的高深难懂. 委托的使用 例一: 什么是委托? 个人理解:用来传递方法的类型.(用来传递数字的类型有int.float ...

  5. 再讲IQueryable<T>,揭开表达式树的神秘面纱

    接上篇<先说IEnumerable,我们每天用的foreach你真的懂它吗?> 最近园子里定制自己的orm那是一个风生水起,感觉不整个自己的orm都不好意思继续混博客园了(开个玩笑).那么 ...

  6. Linq表达式、Lambda表达式你更喜欢哪个?

    什么是Linq表达式?什么是Lambda表达式? 如图: 由此可见Linq表达式和Lambda表达式并没有什么可比性. 那与Lambda表达式相关的整条语句称作什么呢?在微软并没有给出官方的命名,在& ...

  7. 背后的故事之 - 快乐的Lambda表达式(一)

    快乐的Lambda表达式(二) 自从Lambda随.NET Framework3.5出现在.NET开发者眼前以来,它已经给我们带来了太多的欣喜.它优雅,对开发者更友好,能提高开发效率,天啊!它还有可能 ...

  8. Kotlin的Lambda表达式以及它们怎样简化Android开发(KAD 07)

    作者:Antonio Leiva 时间:Jan 5, 2017 原文链接:https://antonioleiva.com/lambdas-kotlin/ 由于Lambda表达式允许更简单的方式建模式 ...

  9. SQL Server-表表达式基础回顾(二十四)

    前言 从这一节开始我们开始进入表表达式章节的学习,Microsoft SQL Server支持4种类型的表表达式:派生表.公用表表达式(CTE).视图.内嵌表值函数(TVF).简短的内容,深入的理解, ...

随机推荐

  1. 【转】linux sed命令

    转自:linux sed命令就是这么简单 参考:Linux三大剑客之sed:https://blog.csdn.net/solaraceboy/article/details/79272344 阅读目 ...

  2. vmware ubuntu16 启动蓝屏屏幕闪

    vmware ubuntu16 启动蓝屏屏幕闪 虚拟机安装了ubuntu16 desktop,没有关闭自动更新: 结果关机虚拟机时出现等5秒更新,类似win10关机更新: 再开机发现就蓝屏了,多次重启 ...

  3. SELECT DISTINCT ON expressions must match initial ORDER BY expressions

    开发说pg中执行sql报错,发来消息让帮看看: SELECT DISTINCT ON expressions must match initial ORDER BY expressions 详细语句如 ...

  4. 【Python】解析Python中的线程与进程

    基础知识 线程 进程 两者的区别 线程的类型 Python 多线程 GIL 创建多线程 线程合并 线程同步与互斥锁 可重入锁(递归锁) 守护线程 定时器 Python 多进程 创建多进程 多进程通信 ...

  5. http状态码610,613

    610  请求超时 613  dns解析错误

  6. JAVA中使用LDAP登录的三种方式

    搜索中关于java 登录ldap,大部分会采用  cn=xxx,ou=xxx,dc=xxx的方式,此处的cn是用户的Display Name,而不是account,而且如果ou有多层,比如我们的OU就 ...

  7. windows cmd ftp 自动下载

    1.编写ftp的bat脚本: set year=%,% set day=%,%%,%%,% mkdir d:\ftp\%,% mkdir d:\ftp\%,%\%,%%,%%,% del d:\ftp ...

  8. VS2017 winform 打包 安装(使用 Microsoft Visual Studio 2017 Installer Project)

    Microsoft Visual Studio 2017 Installer Projects SkyRiN发表于Coding+订阅 253 助力数字生态,云产品优惠大促 腾讯云促销,1核1G 99元 ...

  9. oracle 数据库RPM安装方式

    下载RPM包 Oracle Database Software Downloads 下载Linux x86-64 对应的RPM oracle-database-ee-19c-1.0-1.x86_64. ...

  10. python -m SimpleHTTPServer搭建简单HTTP服务

    PYTHON自带HTTP服务,命令: python -m SimpleHTTPServer 使用上述命令将当前目录发布到8000端口,为当前进行,不是后台运行 指定端口: python -m Simp ...