以前棧長分享過 Java 8 一系列新特性的文章,其中重點介紹了 Stream.java
獲取上面這份 Java 8~12 系列新特性乾貨文章,請在微信搜索關注微信公衆號:Java技術棧,在公衆號後臺回覆:java。數組
今天來分享下在 Java 8 中建立 Stream 的 10 種方式,我就整理了 10 種,其實還有更多,僅供你們參考學習下。微信
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()));
程序輸出:spa
stream2:ABC
看 Stream.of 源碼,上面這兩種方式其實就是第三種方式的包裝版。code
public static<T> Stream<T> of(T... values) { return Arrays.stream(values); }
咱們直接使用源碼中的方式也是同樣的。rem
String[] values = new String[]{"A", "B", "C"}; Stream<String> stream3 = Arrays.stream(values); System.out.println("stream3:" + stream3.collect(joining()));
程序輸出:get
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()));
程序輸出:it
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
好了,這是棧長整理的 10 種建立 Stream 的方式,是否是很騷?若是你還知道其餘的騷操做,能夠留言告訴你們,讓你們記住你的頭像和ID。
轉發分享一下吧,我保證你往後總有機會用得着的。
大量 Java 8~12 的新特性文章我正在編寫中,棧長將陸續分享出來,微信搜索關注微信公衆號:Java技術棧,公衆號將第一時間推送,不要錯過。
本文原創首發於微信公衆號:Java技術棧(id:javastack),轉載請原樣保留本信息。