//异步线程
CompletableFuture.runAsync(()->{
businessInternalService.createAccount(contractId);
});
//获取当前时间一周
Map<String,Date> map = DateUtils.getLastWeek(new Date(), 0);
//获取日期
List<Date> mapValuesList = new ArrayList<Date>(map.values());
//无返回值
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
min
//返回类型不一样
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());
//同步
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