您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。