• Java8stream表达式


    //异步线程
    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
    //转换之前 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

  • 相关阅读:
    应用运维职业现状
    两年工作总结
    explicit用法
    最小生成树 之 CODE[VS] 1231 最优布线问题
    最小生成树 之 CODE[VS] 1078 最小生成树
    并查集 之 CODE[VS] 1073 家族
    贪心 + 并查集 之 CODE[VS] 1069 关押罪犯 2010年NOIP全国联赛提高组
    枚举+并查集 之 CODE[VS] 1001 舒适的路线 2006年
    SPFA算法(求解单源最短路)详解 + 最短路 之 CODE[VS] 1079 回家
    最短路 之 CODE[VS] 1041 Car的旅行路线 2001年NOIP全国联赛提高组
  • 原文地址:https://www.cnblogs.com/ywsheng/p/11236521.html
Copyright © 2020-2023  润新知