JAVA在JDK1.8中Stream流的使用


 

 

 

 

 

 

 

 

Stream流的map使用

轉換大寫

 List<String> list3 = Arrays.asList("zhangSan", "liSi", "wangWu");
 System.out.println("轉換之前的數據:" + list3);
 List<String> list4 = list3.stream().map(String::toUpperCase).collect(Collectors.toList());
 System.out.println("轉換之后的數據:" + list4); 
 // 轉換之后的數據:[ZHANGSAN, LISI,WANGWU]

 

轉換數據類型

List<String> list31 = Arrays.asList("1", "2", "3");
 System.out.println("轉換之前的數據:" + list31);
 List<Integer> list41 = list31.stream().map(Integer::valueOf).collect(Collectors.toList());
 System.out.println("轉換之后的數據:" + list41); 
 // [1, 2, 3]

 

獲取平方

List<Integer> list5 = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 });
 List<Integer> list6 = list5.stream().map(n -> n * n).collect(Collectors.toList());
 System.out.println("平方的數據:" + list6);
 // [1, 4, 9, 16, 25]

 

 

Stream流的filter使用  用於通過設置的條件過濾出元素

 

通過與 findAny 得到 if/else 的值

List<String> list = Arrays.asList("張三", "李四", "王五", "xuwujing");
String result3 = list.stream().filter(str -> "李四".equals(str)).findAny().orElse("找不到!");
String result4 = list.stream().filter(str -> "李二".equals(str)).findAny().orElse("找不到!");

System.out.println("stream 過濾之后 2:" + result3);
System.out.println("stream 過濾之后 3:" + result4);
//stream 過濾之后 2:李四
//stream 過濾之后 3:找不到!

 

 

通過與 mapToInt 計算和

 List<User> lists = new ArrayList<User>();
 lists.add(new User(6, "張三"));
 lists.add(new User(2, "李四"));
 lists.add(new User(3, "王五"));
 lists.add(new User(1, "張三"));
 // 計算這個list中出現 "張三" id的值
 int sum = lists.stream().filter(u -> "張三".equals(u.getName())).mapToInt(u -> u.getId()).sum();

 System.out.println("計算結果:" + sum); 
 // 7

 

Stream流的flatMap使用   用於映射每個元素到對應的結果,一對多。

 

從句子中得到單詞

 String worlds = "The way of the future";
 List<String> list7 = new ArrayList<>();
 list7.add(worlds);
 List<String> list8 = list7.stream().flatMap(str -> Stream.of(str.split(" ")))
   .filter(world -> world.length() > 0).collect(Collectors.toList());
 System.out.println("單詞:");
 list8.forEach(System.out::println);
 // 單詞:
 // The 
 // way 
 // of 
 // the 
 // future

 

 

Stream流的limit使用 用於獲取指定數量的流

 

獲取前n條數的數據

 Random rd = new Random();
 System.out.println("取到的前三條數據:");
 rd.ints().limit(3).forEach(System.out::println);
 // 取到的前三條數據:
 // 1167267754
 // -1164558977
 // 1977868798

 

結合skip使用得到需要的數據

skip表示的是扔掉前n個元素。

 

List<User> list9 = new ArrayList<User>();
 for (int i = 1; i < 4; i++) {
  User user = new User(i, "pancm" + i);
  list9.add(user);
 }
 System.out.println("截取之前的數據:");
 // 取前3條數據,但是扔掉了前面的2條,可以理解為拿到的數據為 2<=i<3 (i 是數值下標)
 List<String> list10 = list9.stream().map(User::getName).limit(3).skip(2).collect(Collectors.toList());
 System.out.println("截取之后的數據:" + list10);
 //  截取之前的數據:
 //  姓名:pancm1
 //  姓名:pancm2
 //  姓名:pancm3
 //  截取之后的數據:[pancm3]

 

 

Stream流的sort使用

Random rd2 = new Random();
 System.out.println("取到的前三條數據然后進行排序:");
 rd2.ints().limit(3).sorted().forEach(System.out::println);
 // 取到的前三條數據然后進行排序:
 // -2043456377
 // -1778595703
 // 1013369565

 

優化排序

//普通的排序取值
 List<User> list11 = list9.stream().sorted((u1, u2) -> u1.getName().compareTo(u2.getName())).limit(3)
   .collect(Collectors.toList());
 System.out.println("排序之后的數據:" + list11);
 //優化排序取值
 List<User> list12 = list9.stream().limit(3).sorted((u1, u2) -> u1.getName().compareTo(u2.getName()))
   .collect(Collectors.toList());
 System.out.println("優化排序之后的數據:" + list12);
 //排序之后的數據:[{"id":1,"name":"pancm1"}, {"id":2,"name":"pancm2"}, {"id":3,"name":"pancm3"}]
 //優化排序之后的數據:[{"id":1,"name":"pancm1"}, {"id":2,"name":"pancm2"}, {"id":3,"name":"pancm3"}]

 

 

Stream流的max/min/distinct使用

 

得到最大最小值

List<String> list13 = Arrays.asList("zhangsan","lisi","wangwu","xuwujing");
 int maxLines = list13.stream().mapToInt(String::length).max().getAsInt();
 int minLines = list13.stream().mapToInt(String::length).min().getAsInt();
 System.out.println("最長字符的長度:" + maxLines+",最短字符的長度:"+minLines);
 //最長字符的長度:8,最短字符的長度:4

 

得到去重之后的數據

 String lines = "good good study day day up";
 List<String> list14 = new ArrayList<String>();
 list14.add(lines);
 List<String> words = list14.stream().flatMap(line -> Stream.of(line.split(" "))).filter(word -> word.length() > 0)
   .map(String::toLowerCase).distinct().sorted().collect(Collectors.toList());
 System.out.println("去重復之后:" + words);
 //去重復之后:[day, good, study, up]

 

 

Stream流的Match使用

 

  • allMatch:Stream 中全部元素符合則返回 true ;
  • anyMatch:Stream 中只要有一個元素符合則返回 true;
  • noneMatch:Stream 中沒有一個元素符合則返回 true。

 

數據是否符合

 boolean all = lists.stream().allMatch(u -> u.getId() > 3);
 System.out.println("是否都大於3:" + all);
 boolean any = lists.stream().anyMatch(u -> u.getId() > 3);
 System.out.println("是否有一個大於3:" + any);
 boolean none = lists.stream().noneMatch(u -> u.getId() > 3);
 System.out.println("是否沒有一個大於3的:" + none);  
 // 是否都大於3:false
 // 是否有一個大於3:true
 // 是否沒有一個大於3的:false

 

 

Stream流的reduce使用 主要作用是把 Stream 元素組合起來進行操作。

 

字符串連接

String concat = Stream.of("A", "B", "C", "D").reduce("", String::concat);
System.out.println("字符串拼接:" + concat);

 

得到最小值

 double minValue = Stream.of(-4.0, 1.0, 3.0, -2.0).reduce(Double.MAX_VALUE, Double::min);
 System.out.println("最小值:" + minValue);
 //最小值:-4.0

 

求和

// 求和, 無起始值
 int sumValue = Stream.of(1, 2, 3, 4).reduce(Integer::sum).get();
 System.out.println("有無起始值求和:" + sumValue);
 // 求和, 有起始值
  sumValue = Stream.of(1, 2, 3, 4).reduce(1, Integer::sum);
  System.out.println("有起始值求和:" + sumValue);
 // 有無起始值求和:10
 // 有起始值求和:11

 

 

過濾拼接

concat = Stream.of("a", "B", "c", "D", "e", "F").filter(x -> x.compareTo("Z") > 0).reduce("", String::concat);
System.out.println("過濾和字符串連接:" + concat);
 //過濾和字符串連接:ace

 

Stream流的groupingBy/partitioningBy使用

  • groupingBy:分組排序;
  • partitioningBy:分區排序。

 

分組排序

System.out.println("通過id進行分組排序:");
 Map<Integer, List<User>> personGroups = Stream.generate(new UserSupplier2()).limit(5)
   .collect(Collectors.groupingBy(User::getId));
 Iterator it = personGroups.entrySet().iterator();
 while (it.hasNext()) {
  Map.Entry<Integer, List<User>> persons = (Map.Entry) it.next();
  System.out.println("id " + persons.getKey() + " = " + persons.getValue());
 }
 
 // 通過id進行分組排序:
 // id 10 = [{"id":10,"name":"pancm1"}] 
 // id 11 = [{"id":11,"name":"pancm3"}, {"id":11,"name":"pancm6"}, {"id":11,"name":"pancm4"}, {"id":11,"name":"pancm7"}]



 class UserSupplier2 implements Supplier<User> {
  private int index = 10;
  private Random random = new Random();
 
  @Override
  public User get() {
   return new User(index % 2 == 0 ? index++ : index, "pancm" + random.nextInt(10));
  }
 }

 

 

分區排序

 System.out.println("通過年齡進行分區排序:");
 Map<Boolean, List<User>> children = Stream.generate(new UserSupplier3()).limit(5)
   .collect(Collectors.partitioningBy(p -> p.getId() < 18));

 System.out.println("小孩: " + children.get(true));
 System.out.println("成年人: " + children.get(false));
 
 // 通過年齡進行分區排序:
 // 小孩: [{"id":16,"name":"pancm7"}, {"id":17,"name":"pancm2"}]
 // 成年人: [{"id":18,"name":"pancm4"}, {"id":19,"name":"pancm9"}, {"id":20,"name":"pancm6"}]

  class UserSupplier3 implements Supplier<User> {
  private int index = 16;
  private Random random = new Random();
 
  @Override
  public User get() {
   return new User(index++, "pancm" + random.nextInt(10));
  }
 }

 

 

Stream流的summaryStatistics使用  IntSummaryStatistics 用於收集統計信息(如count、min、max、sum和average)的狀態對象。

 

得到最大、最小、之和以及平均數。

 List<Integer> numbers = Arrays.asList(1, 5, 7, 3, 9);
 IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics();
  
 System.out.println("列表中最大的數 : " + stats.getMax());
 System.out.println("列表中最小的數 : " + stats.getMin());
 System.out.println("所有數之和 : " + stats.getSum());
 System.out.println("平均數 : " + stats.getAverage());
 
 // 列表中最大的數 : 9
 // 列表中最小的數 : 1
 // 所有數之和 : 25
 // 平均數 : 5.0

 


免責聲明!

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



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