Java 中帶有流篩選的列表總和


要在 Java 中取得帶流篩選的列表總和,程式碼如下 −

示例

 線上演示

import java.util.*;
public class Demo
{
   public static void main(String[] args)
   {
      List<Integer> my_list = new ArrayList<Integer>();
      my_list.add(11);
      my_list.add(35);
      my_list.add(56);
      my_list.add(78);
      my_list.add(91);
      System.out.println(sum(my_list));
   }
   public static int sum(List<Integer> my_list)
   {
      System.out.println("In the main function, the sum of list with filter is ");
      return my_list.stream().filter(i -> i > 5).mapToInt(i -> i).sum();
   }
}

輸出

In the main function, the sum of list with filter is
271

一個名為 Demo 的類包含建立 ArrayList 的主函式。使用“add()”函式將元素新增到 ArrayList 中。可以使用“sum”函式將列表的所有元素的總和列印在螢幕上。定義了另一個名為“sum”的函式,它透過將值對映到整數來返回篩選後的輸出。

更新於: 2020 年 7 月 13 日

845 次瀏覽

啟動你的 職業生涯

透過完成課程取得認證

開始
廣告
© . All rights reserved.