Java8stream表达式

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");
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));








上一篇:Java8 那些事儿(一):Stream 函数式编程


下一篇:Java8的Stream API使用