java8中如何创建stream流呢?

java-教程王 Java经验 发布时间:2022-04-13 21:49:56 阅读数:8099 1
下文笔者讲述Java代码创建stream流的方法分享,如下所示:

Stream.of可变参数的创建方式

Stream<String> stream1 = Stream.of("java265.com", "java265.com-2", "java265.com-3");
System.out.println("stream1:" + stream1.collect(joining()));

Stream.of 使用数组的方式创建

String[] values = new String[]{"java265.com", "java265.com-2", "java265.com-3"};
Stream<String> stream2 = Stream.of(values);
System.out.println("stream2:" + stream2.collect(joining()));

Stream ...的方式创建

String[] values = new String[]{"java265.com", "java265.com-2", "java265.com-3"};
Stream<String> stream3 = Stream.of(values);
System.out.println("stream3:" + stream3.collect(joining()));

list创建stream

List创建stream,也是我们最常用的一种方式

List<String> list = Arrays.asList("java265.com", "java265.com-2", "java265.com-3");
Stream<String> stream4 = list.stream();
System.out.println("stream4:" + stream4.collect(joining()));

set创建stream

Set<String> set = new HashSet<>(Arrays.asList("java265.com", "java265.com-2", "java265.com-3"));
Stream<String> stream5 = set.stream();
System.out.println("stream5:" + stream5.collect(joining()));

map创建stream

Map<String, String> map = new HashMap<>();
map.put("1", "java265.com");
map.put("2", "java265.com-2");
map.put("3", "java265.com-3");
Stream<String> stream6 = map.values().stream();
System.out.println("stream6:" + stream6.collect(joining()));

Stream.iterate的方式创建stream

Stream<String> stream7 = Stream.iterate("A", e -> String.valueOf((char) (e.charAt(0) + 1))).limit(3);
System.out.println("stream7:" + stream7.collect(joining()));

Pattern

String value = "java265.com java265.com-1 java265.com-2";
Stream<String> stream8 = Pattern.compile("\\W").splitAsStream(value);
System.out.println("stream8:" + stream8.collect(joining()));

Files.lines

try {
    Stream<String> stream9 = Files.lines(Paths.get("d:\test.txt"));
    System.out.println("stream9:" + stream9.collect(joining()));
} catch (IOException e) {
    e.printStackTrace();
}

Stream.generate

Stream<String> stream10 = Stream.generate(() -> "Q").limit(3);
System.out.println("stream10:" + stream10.collect(joining()));
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202204/16498578492855.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者