MultiThread/multithreading1/src/main/java/cn/bunny/stream/StreamExample01.java

60 lines
1.8 KiB
Java

package cn.bunny.stream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class StreamExample01 {
public static void main(String[] args) throws IOException {
Stream<Integer> build = Stream.<Integer>builder()
.add(1)
.add(12)
.add(3)
.add(34)
.build();
Stream<Integer> integerStream = Stream.of(1, 2, 34, 5);
// 空Stream
Stream<Object> objectStream = Stream.empty();
// Stream.generate创建
Stream.generate(() -> ThreadLocalRandom.current().nextInt(10))
.limit(10)
.forEach(System.out::println);
// 不加限制会一直创建
Stream.iterate(100, seed -> seed + 1)
.limit(10)
.forEach(System.out::println);
// IntStream创建[1,10)
IntStream.range(1, 10)
.forEach(System.out::println);
// 创建闭区间[1,10]
IntStream.rangeClosed(1, 10)
.forEach(System.out::println);
// Arrays.asList创建
Arrays.asList("a", "b", "c", "d", "e", "f")
.forEach(System.out::println);
// 创建Stream<Map.Entry<String, String>>
Stream<Map.Entry<String, String>> stream = new HashMap<String, String>() {{
put("a", "b");
put("c", "d");
}}.entrySet().stream();
// Files中的Stream
Stream<String> lines = Files.lines(Paths.get("xxx.md"), StandardCharsets.UTF_8);
}
}