慕侠2389804
以下是如何在 Java 8+ 中使用流来实现这一点。 int nValues = 5; int minValue = 1; int maxValue = 30; Random r = new Random(); for (int i = 0; i < 10; i++) { int[] values = r.ints(nValues, minValue, maxValue + 1).toArray(); // min to sum is the threshold int minToSum = r.nextInt(7) + 10; // between 10 an 16 inclusive int sum = Arrays.stream(values).filter(m -> m > minToSum).sum(); System.out.println("sum = " + sum + " for greater than " + minToSum + " : " + Arrays.toString(values)); }以下输出。sum = 65 for values greater than 11 : [2, 10, 14, 23, 28]sum = 92 for values greater than 10 : [13, 18, 15, 19, 27]sum = 94 for values greater than 12 : [25, 6, 14, 25, 30]sum = 54 for values greater than 10 : [14, 8, 14, 26, 5]sum = 22 for values greater than 15 : [15, 8, 13, 22, 14]sum = 28 for values greater than 13 : [3, 28, 9, 6, 5]sum = 87 for values greater than 13 : [5, 18, 25, 21, 23]sum = 31 for values greater than 13 : [16, 7, 12, 2, 15]sum = 42 for values greater than 15 : [7, 22, 20, 10, 5]sum = 40 for values greater than 12 : [2, 2, 13, 27, 9]