Java8中怎么创建Stream
Java 8中怎么创建 Stream ,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
创新互联专注于嘉峪关企业网站建设,自适应网站建设,商城系统网站开发。嘉峪关网站建设公司,为嘉峪关等地区提供建站服务。全流程定制网站制作,专业设计,全程项目跟踪,创新互联专业和态度为您提供的服务
1、Stream.of 可变参数
Streamstream1 = Stream.of("A", "B", "C"); System.out.println("stream1:" + stream1.collect(joining()));
程序输出:
stream1:ABC
2、Stream.of 数组
String[] values = new String[]{"A", "B", "C"}; Streamstream2 = Stream.of(values); System.out.println("stream2:" + stream2.collect(joining()));
程序输出:
stream2:ABC
看 Stream.of 源码,上面这两种方式其实就是第三种方式的包装版。
public staticStream of(T... values) { return Arrays.stream(values); }
我们直接使用源码中的方式也是一样的。
3、Arrays.stream
String[] values = new String[]{"A", "B", "C"}; Streamstream3 = Arrays.stream(values); System.out.println("stream3:" + stream3.collect(joining()));
程序输出:
stream3:ABC
4、List
Listlist = Arrays.asList("A", "B", "C"); Stream stream4 = list.stream(); System.out.println("stream4:" + stream4.collect(joining()));
程序输出:
stream4:ABC
5、Set
Setset = new HashSet<>(Arrays.asList("A", "B", "C")); Stream stream5 = set.stream(); System.out.println("stream5:" + stream5.collect(joining()));
程序输出:
stream5:ABC
6、Map
Mapmap = new HashMap<>(); map.put("1", "A"); map.put("2", "B"); map.put("3", "C"); Stream stream6 = map.values().stream(); System.out.println("stream6:" + stream6.collect(joining()));
程序输出:
stream6:ABC
7、Stream.iterate
Streamstream7 = Stream.iterate("A", e -> String.valueOf((char) (e.charAt(0) + 1))).limit(3); System.out.println("stream7:" + stream7.collect(joining()));
程序输出:
stream7:ABC
8、Pattern
String value = "A B C"; Streamstream8 = Pattern.compile("\\W").splitAsStream(value); System.out.println("stream8:" + stream8.collect(joining()));
程序输出:
stream8:ABC
9、Files.lines
try { Streamstream9 = Files.lines(Paths.get("d:/data.txt")); System.out.println("stream9:" + stream9.collect(joining())); } catch (IOException e) { e.printStackTrace(); }
data.txt文件内容如下:
A B C
程序输出:
stream9:ABC
10、Stream.generate
Streamstream10 = Stream.generate(() -> "A").limit(3); System.out.println("stream10:" + stream10.collect(joining()));
程序输出:
stream10:AAA
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注创新互联行业资讯频道,感谢您对创新互联的支持。
网站栏目:Java8中怎么创建Stream
标题链接:http://scyanting.com/article/pjsccs.html