簡體   English   中英

如何轉換“流<string> " 到 "字符串"</string>

[英]How to convert "Stream<String>" to "String"

我想將Stream<String>轉換為String並打印所有字符串。

Stream<String> result= Stream.of("do","re","ma","po","fa","si")
                             .filter(str -> str.length()>5)
                             .peek(System.out:: println);
                           //.allMatch(str -> str.length() >5);

System.out.println(result);

這里下來 output 我得到

java.util.Spliterators$1Adapter@63961c42

結果是打印object但不是String ,並且在轉換為toString()時也打印相同但如何打印為字符串

在 java 8 中,有方法加入() ,它是收集器 class的一部分。 您必須使用Collectors.joining()加入此字符串。

下面是代碼:

String result = Stream.of("do", "re", "ma", "po", "fa", "si")
                .filter(str -> str.length() > 1)
                .collect(Collectors.joining());

或者

String result= Stream.of("do","re","ma","po","fa","si")
                .filter(str -> str.length() > 1)
                .peek(System.out::println)
                .collect(Collectors.joining());

你在尋找這樣的東西嗎?

    String result = Stream.of("do","re","ma","po","fa","si").
                collect(Collectors.joining(""));
    System.out.println(result);

Output:

doremapofasi

或者:

        String result = Stream.of("do", "re", "ma", "po", "fa", "si")
            .filter(str -> str.length() > 1)
            .peek(System.out::println)
            .collect(Collectors.joining(""));
        System.out.println(result);

Output:

do
re
ma
po
fa
si
doremapofasi

您誤解了Stream API背后的機制。

A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc), zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate) ) 和終端操作(產生結果或副作用,例如 count() 或 forEach(Consumer))。 Streams are lazy only performed when the terminal operation is initiated對源數據進行computation ,並且僅在需要時消耗源元素。

主要結論:

只有if the terminal operation is initiated才會對管道中的數據進行操作。

從編譯器的角度來看,沒有終端操作的 Stream 是完全有效的。 它會編譯,但不會執行。

您嘗試打印的內容( java.util.Spliterators$1Adapter@63961c42 )不是結果,而是 stream ZA8CFDE6331BD59EB26666F8911CB 本身。

要產生結果或副作用,流管道必須以終端操作結束( collect()reduce()count()forEach()findFirst()findAnyanyMatch() - 在您的代碼中注釋掉)。 請注意, peek()是一個中間操作,並將其與forEach()混淆。 您可以根據需要多次使用peek() ,這對於調試目的很有用。

    public static void main(String[] args) {

        String result = getStream()
                .filter(str -> str.length() > 5 && str.length() < 8)
                .findFirst() // that will produce a single result that may or may not be present
                .orElseThrow(); // action for the case if result is not present

        System.out.println("Single result: " + result + "\n");

        getStream()
                .filter(str -> str.contains("a"))
                .peek(System.out::println) // intermediate operation that will print every element that matches the first filter
                .filter(str -> str.length() > 8)
                .forEach(System.out::println); // terminal operation that prints every element remained after processing the pipeline
    }

    private static Stream<String> getStream() {
        return Stream.of("Ignoranti", "quem", "portum", "petat", "nullus", "suus", "ventus", "est");
    }

output

Single result: portum

Ignoranti
Ignoranti
petat

如果您真的只想打印元素而不是返回它們,您可以

Stream.of("do","re","ma","po","fa","si")
    .filter(str -> str.length()>5)
    .forEach(System.out:: println);

forEach也是 stream 上的“終止”操作,這意味着它“實際執行”它。

您需要通過調用 collect 或 reduce 來“執行” stream

assertEquals("ab", Arrays.stream(new String[]{"a", "b"}).reduce("", (s,x) -> s + x));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM