Java8 新特性之流式資料處理

來源:互聯網
上載者:User

標籤:public   機械   center   姓名   Collector   uid   電腦   image   上海   

流中間操作

操 作 類 型 傳回型別 巨集指令引數 函數描述符
filter 中間 Stream Predicate T -> boolean
map 中間 Stream Function<T ,R> T -> R
limit 中間 Stream
sorted 中間 Stream Comparator (T ,T) -> int
distinct 中間 Stream
flatMap 中間 Stream Function<T ,Stream T -> Stream
終端操作
操作 類型 傳回型別 巨集指令引數 函數描述符
forEach 終端 void Consumer T -> void
count 終端 Long
collect 終端 R Collector<T ,A ,R>
anyMatch 終端 boolean Predicate T -> boolean
allMatch 終端 boolean Predicate< T> T -> boolean
noneMatch 終端 boolean Predicate T -> boolean
findAny 終端 Optional
findFirst 終端 Optional
reduce 終端 Optional BinaryOperator (T, T) -> T



Action Start初始化
@Data@AllArgsConstructorpublic class Employee implements Serializable {   private static final long serialVersionUID = -8078550089934349371L;   private Long id;   /**    * 姓名    */   private String name;   /**    * 年齡    */   private Integer age;   /**    * 部門    */   private String department;   /**    * 專業    */   private String profession;   /**    * 地址    */   private String Address;}
public static List<Employee> employees = Collections.unmodifiableList(Arrays.asList(   new Employee(1L, "張三", 18, "技術開發中心", "電腦科學", "江西南昌"),   new Employee(2L, "李四", 18, "技術開發中心", "電腦科學", "江西撫州"),   new Employee(3L, "王五", 22, "人力行政中心", "土木工程", "北京"),   new Employee(4L, "趙六", 23, "財務管理中心", "經濟管理", "廣東廣州"),   new Employee(5L, "田七", 28, "財務管理中心", "機械與自動化", "上海"),   new Employee(5L, "田七", 28, "財務管理中心", "機械與自動化", "上海"),   new Employee(6L, "孔明", 26, "戰略合作事業部", "生化工程", "廣東深圳"),   new Employee(7L, "玄德", 40, "戰略合作事業部", "生命科學", "江蘇南京"),   new Employee(8L, "雲長", 33, "客戶服務部", "社會學", "廣東廣州"),   new Employee(9L, "翼德", 28, "智能金融事業部", "經濟管理", "江蘇南京"),   new Employee(10L, "魯肅", 36, "智能金融事業部", "經濟管理", "上海")));

1.0 過濾

  • filter 篩選年齡小於25的員工

    List<Employee> list = employees.stream()          .filter(employee -> employee.getAge() > 25)          .collect(Collectors.toList());
  • distinct 篩選重複元素

    List<Employee> list = employees.stream()            .filter(employee -> employee.getAge() > 25)            .distinct()            .collect(Collectors.toList());
  • limit 截斷流

List<Employee> list = employees.stream()           .filter(employee -> employee.getAge() > 25)           .limit(3)           .collect(Collectors.toList());
  • ? skip 跳過元素
List<Employee> list = employees.stream()               .filter(employee -> employee.getAge() > 25)               .skip(2)               .collect(Collectors.toList());

2.0 映射

  • map 擷取所有員工的姓名

    List<String> list = employees.stream()          .map(Employee::getName)          .collect(Collectors.toList());
  • flatMap 扁平流

    String[] arrays = {"Hello", "World"};List<String> list = Arrays.stream(arrays)            .map(str -> str.split("")) // 映射成為Stream<String[]>            .flatMap(Arrays::stream) // 扁平化為Stream<String>            .distinct()            .collect(Collectors.toList());

3.0 尋找和匹配

  • anyMatch 流中是否有一個元素能匹配給定的謂詞 返回 boolean

    boolean result = employees.stream()         .anyMatch(employee -> employee.getAge() == 28);
  • allMatch 流中的所有元素能否符合條件

     boolean result = employees.stream()         .allMatch(employee -> employee.getAge() < 35);
  • noneMatch 可以確保流中沒有任何元素與給定的謂詞匹配

    boolean result = employees.stream()       .noneMatch(employee -> employee.getAge() > 40);
  • findAny 返回當前流中的任意元素

    Optional<Employee> result = employees.stream()           .filter(employee -> Objects.equals(employee.getProfession(), "電腦科學"))           .findAny();
  • findFirst 返回當前流中的第一個元素

    Optional<Employee> result = employees.stream()           .filter(employee -> Objects.equals(employee.getProfession(), "電腦科學"))           .findFirst();

    你可能會想,為什麼會同時有 findFirst 和 findAny 呢?答案是並行。找到第一個元素在並行上限制更多。如果你不關心返回的元素是哪個,請使用 findAny ,因為它在使用並行流時限制較少.

4.0 歸約

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);// 計算數值總合// 方式一Integer result1 = numbers.stream().reduce(0, (a, b) -> a + b);// 方式二Integer result2 = numbers.stream().reduce(0, Integer::sum);// 計算最大值Optional<Integer> min = numbers.stream().reduce(Integer::min);// 計算最小值Optional<Integer> min = numbers.stream().reduce(Integer::max);

5.0 收集器

  • eg : 計算 員工總數
long count = employees.stream().count();Long count = employees.stream().collect(Collectors.counting());
  • eg : 尋找 員工中年齡最大的

    Optional<Employee> employee = employees.stream()          .collect(Collectors.maxBy(Comparator.comparing(Employee::getAge)));Optional<Employee> employee = employees.stream()             .max(Comparator.comparing(Employee::getAge));
  • eg: 員工年齡匯總

    Integer sum = employees.stream()          .mapToInt(Employee::getAge).sum();Integer sum = employees.stream()          .collect(Collectors.summingInt(Employee::getAge));
  • eg : 員工平均值

    Double averaging = employees.stream().collect(Collectors.averagingInt(Employee::getAge))

6.0 分組

  • eg : 員工 按專業進行分組

    Map<String, List<Employee>> map = employees.stream()          .collect(Collectors.groupingBy(Employee::getProfession));
  • eg : 員工 按專業進行分組 並統計專業人數

    Map<String, Long> map = employees.stream()          .collect(Collectors.groupingBy(Employee::getProfession, Collectors.counting()));
  • eg : 按專業進行分組 並尋找專業中年齡最大的那人

 Map<String, Optional<Employee>> map = employees.stream().collect(           Collectors.groupingBy(Employee::getProfession,                                                          Collectors.maxBy(Comparator.comparing(Employee::getAge))));
  • eg : 將收集器結果轉換成 另一種類型 Collectors.collectingAndThen

    Map<String, Employee> map = employees.stream().collect( Collectors.groupingBy(Employee::getProfession,Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(Employee::getAge)),Optional::get)));
  • eg : 將收集器映射成具體的對象

    Map<String, Set<Integer>> map = employees.stream().collect(          Collectors.groupingBy(Employee::getProfession, Collectors.mapping(Employee::getAge, Collectors.toSet())));

    ?

Java8 新特性之流式資料處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.