Java 8中怎么創(chuàng)建 Stream ,很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
創(chuàng)新互聯(lián)專注于嘉峪關(guān)企業(yè)網(wǎng)站建設(shè),自適應(yīng)網(wǎng)站建設(shè),商城系統(tǒng)網(wǎng)站開發(fā)。嘉峪關(guān)網(wǎng)站建設(shè)公司,為嘉峪關(guān)等地區(qū)提供建站服務(wù)。全流程定制網(wǎng)站制作,專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)
Streamstream1 = Stream.of("A", "B", "C"); System.out.println("stream1:" + stream1.collect(joining()));
程序輸出:
stream1:ABC
String[] values = new String[]{"A", "B", "C"}; Streamstream2 = Stream.of(values); System.out.println("stream2:" + stream2.collect(joining()));
程序輸出:
stream2:ABC
看 Stream.of 源碼,上面這兩種方式其實(shí)就是第三種方式的包裝版。
public staticStream of(T... values) { return Arrays.stream(values); }
我們直接使用源碼中的方式也是一樣的。
String[] values = new String[]{"A", "B", "C"}; Streamstream3 = Arrays.stream(values); System.out.println("stream3:" + stream3.collect(joining()));
程序輸出:
stream3:ABC
Listlist = Arrays.asList("A", "B", "C"); Stream stream4 = list.stream(); System.out.println("stream4:" + stream4.collect(joining()));
程序輸出:
stream4:ABC
Setset = new HashSet<>(Arrays.asList("A", "B", "C")); Stream stream5 = set.stream(); System.out.println("stream5:" + stream5.collect(joining()));
程序輸出:
stream5:ABC
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
Streamstream7 = 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"; Streamstream8 = Pattern.compile("\\W").splitAsStream(value); System.out.println("stream8:" + stream8.collect(joining()));
程序輸出:
stream8:ABC
try { Streamstream9 = Files.lines(Paths.get("d:/data.txt")); System.out.println("stream9:" + stream9.collect(joining())); } catch (IOException e) { e.printStackTrace(); }
data.txt文件內(nèi)容如下:
A B C
程序輸出:
stream9:ABC
Streamstream10 = Stream.generate(() -> "A").limit(3); System.out.println("stream10:" + stream10.collect(joining()));
程序輸出:
stream10:AAA
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對(duì)創(chuàng)新互聯(lián)的支持。