Java 8中怎么创建 Stream ,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
Stream<String> stream1 = Stream.of("A", "B", "C"); System.out.println("stream1:" + stream1.collect(joining()));
程序输出:
stream1:ABC
String[] values = new String[]{"A", "B", "C"}; Stream<String> stream2 = Stream.of(values); System.out.println("stream2:" + stream2.collect(joining()));
程序输出:
stream2:ABC
看 Stream.of 源码,上面这两种方式其实就是第三种方式的包装版。
public static<T> Stream<T> of(T... values) { return Arrays.stream(values); }
我们直接使用源码中的方式也是一样的。
String[] values = new String[]{"A", "B", "C"}; Stream<String> stream3 = Arrays.stream(values); System.out.println("stream3:" + stream3.collect(joining()));
程序输出:
stream3:ABC
List<String> list = Arrays.asList("A", "B", "C"); Stream<String> stream4 = list.stream(); System.out.println("stream4:" + stream4.collect(joining()));
程序输出:
stream4:ABC
Set<String> set = new HashSet<>(Arrays.asList("A", "B", "C")); Stream<String> stream5 = set.stream(); System.out.println("stream5:" + stream5.collect(joining()));
程序输出:
stream5:ABC
Map<String, String> map = new HashMap<>(); map.put("1", "A"); map.put("2", "B"); map.put("3", "C"); Stream<String> stream6 = map.values().stream(); System.out.println("stream6:" + stream6.collect(joining()));
程序输出:
stream6:ABC
Stream<String> stream7 = Stream.iterate("A", e -> String.valueOf((char) (e.charAt(0) + 1))).limit(3); System.out.println("stream7:" + stream7.collect(joining()));
程序输出:
stream7:ABC
String value = "A B C"; Stream<String> stream8 = Pattern.compile("\\W").splitAsStream(value); System.out.println("stream8:" + stream8.collect(joining()));
程序输出:
stream8:ABC
try { Stream<String> stream9 = 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
Stream<String> stream10 = Stream.generate(() -> "A").limit(3); System.out.println("stream10:" + stream10.collect(joining()));
程序输出:
stream10:AAA
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。