วิธีแก้ปัญหาด้วยreduce():
int[] array = {23, 3, 56, 97, 42};
// directly print out
Arrays.stream(array).reduce((x, y) -> x > y ? x : y).ifPresent(System.out::println);
// get the result as an int
int res = Arrays.stream(array).reduce((x, y) -> x > y ? x : y).getAsInt();
System.out.println(res);
>>
97
97
ในโค้ดข้างต้นreduce()ส่งกลับข้อมูลในOptionalรูปแบบที่คุณสามารถแปลงไปโดยintgetAsInt()
หากเราต้องการเปรียบเทียบค่าสูงสุดกับจำนวนที่แน่นอนเราสามารถตั้งค่าเริ่มต้นในreduce():
int[] array = {23, 3, 56, 97, 42};
// e.g., compare with 100
int max = Arrays.stream(array).reduce(100, (x, y) -> x > y ? x : y);
System.out.println(max);
>>
100
ในรหัสด้านบนเมื่อreduce()มีการระบุตัวตน (ค่าเริ่มต้น) เป็นพารามิเตอร์แรกมันส่งกลับข้อมูลในรูปแบบเดียวกันกับตัวตน ด้วยคุณสมบัตินี้เราสามารถใช้วิธีนี้กับอาร์เรย์อื่น:
double[] array = {23.1, 3, 56.6, 97, 42};
double max = Arrays.stream(array).reduce(array[0], (x, y) -> x > y ? x : y);
System.out.println(max);
>>
97.0
Collections.max(Arrays.asList())ตามมาด้วย