🚀 feat(新增): Stream的使用

This commit is contained in:
bunny 2024-07-30 16:56:23 +08:00
parent 32bd6284d5
commit a2daab41d0
1 changed files with 42 additions and 0 deletions

View File

@ -0,0 +1,42 @@
package cn.bunny.stream;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Stream;
public class StreamTest {
@Test
void testStream() {
// 产生随机数字流会一直输出
Stream<Double> stream = Stream.generate(Math::random);
stream.forEach(System.out::println);
}
@Test
void internalStream() {
// 一直循环添加
Stream<BigInteger> stream = Stream.iterate(BigInteger.ZERO, n -> n.add(BigInteger.ONE));
stream.forEach(System.out::println);
}
@Test
void testGeneratorLimit() {
// 创建指定长度随机数
List<Double> list = Stream.generate(Math::random).limit(10).toList();
list.forEach(System.out::println);
// 创建不好喊任何元素的流
Stream<Object> empty = Stream.empty();
empty.forEach(System.out::println);
// 创建一个给定值的流
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6);
integerStream.forEach(System.out::println);
// 使用 ofNullable 创建一个流如果值为 null 则创建一个空流
Stream<String> stream = Stream.ofNullable("hello");
stream.forEach(System.out::println);
}
}