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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM