🚀 feat(新增): Stream的使用
This commit is contained in:
parent
ef0e0c12e7
commit
d5784f5337
|
@ -8,6 +8,7 @@ import java.nio.file.Files;
|
|||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class StreamTest {
|
||||
|
@ -158,4 +159,55 @@ public class StreamTest {
|
|||
}); // 迭代所有元素
|
||||
stream.close(); // 在所有操作完成后关闭流
|
||||
}
|
||||
|
||||
// 这两个方法用于获取流中的最大值和最小值。它们通常用于包含可比较元素的流。
|
||||
@Test
|
||||
void minAndMaxTest() {
|
||||
Stream<Integer> numbers = Stream.of(1, 2, 3, 4, 5);
|
||||
|
||||
// 获取流中的最大值
|
||||
Integer max = numbers.max(Integer::compareTo).orElse(0);
|
||||
System.out.println("Max value: " + max);
|
||||
|
||||
// 最小值
|
||||
Stream<Integer> numbers2 = Stream.of(1, 2, 3, 4, 5);
|
||||
Integer min = numbers2.min(Integer::compareTo).orElse(0);
|
||||
System.out.println("Min value: " + min);
|
||||
}
|
||||
|
||||
// 这两个方法用于从流中获取元素。findFirst 返回流中的第一个元素,而 findAny 返回流中的任意一个元素(在并行流中更有用)。
|
||||
@Test
|
||||
void findTest() {
|
||||
Stream<String> strings = Stream.of("apple", "banana", "cherry");
|
||||
|
||||
// 找到第一个元素
|
||||
Optional<String> firstElement = strings.findFirst();
|
||||
System.out.println("First element: " + firstElement.orElse("No element found"));
|
||||
|
||||
// 找到任意一个元素
|
||||
Stream<String> strings2 = Stream.of("apple", "banana", "cherry");
|
||||
Optional<String> anyElement = strings2.findAny();
|
||||
System.out.println("Any element: " + anyElement.orElse("No element found"));
|
||||
}
|
||||
|
||||
// anyMatch:判断流中是否至少有一个元素满足条件。
|
||||
// allMatch:判断流中的所有元素是否都满足条件。
|
||||
// noneMatch:判断流中是否所有元素都不满足条件。
|
||||
@Test
|
||||
void matchTest() {
|
||||
// 检查是否有元素大于3
|
||||
Stream<Integer> numbers = Stream.of(1, 2, 3, 4, 5);
|
||||
boolean anyGreaterThanThree = numbers.anyMatch(num -> num > 3);
|
||||
System.out.println("Any number greater than 3: " + anyGreaterThanThree);
|
||||
|
||||
// 检查是否所有元素都小于10
|
||||
Stream<Integer> numbers2 = Stream.of(1, 2, 3, 4, 5);
|
||||
boolean allLessThanTen = numbers2.allMatch(num -> num < 10);
|
||||
System.out.println("All numbers less than 10: " + allLessThanTen);
|
||||
|
||||
// 检查是否所有元素都不等于0
|
||||
Stream<Integer> numbers3 = Stream.of(1, 2, 3, 4, 5);
|
||||
boolean noneEqualToZero = numbers3.noneMatch(num -> num == 0);
|
||||
System.out.println("No numbers equal to zero: " + noneEqualToZero);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue