簡體   English   中英

如何轉換流 <String[]> 流 <String> ?

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

我試圖將我的String []流展平為String Stream

例如

{ "A", "B", "C" }, {"D, "E" } to "A", "B", "C", "D", "E"

這是我到目前為止的代碼:

Files.lines(Paths.get(file)).map(a -> a.split(" "));

Files.lines(path)返回Stream[String] ,我將每個字符串拆分為“”以獲取所有單詞的數組(所以現在為Stream<String[]>

我想將每個單詞數組展平為單個元素,因此Stream[String]而不是Stream<String[]>

當我使用flatMap而不是map時出現錯誤: Type mismatch: cannot convert from String[] to Stream<? extends Object> Type mismatch: cannot convert from String[] to Stream<? extends Object>

我以為flatMap用於此目的? 什么是完成我想要做的最好的方法


教授提問:

使用流:編寫一個方法,根據長度對文件中的單詞進行分類:

public static Map<Integer,List<String>> wordsByLength(String file) 
throws IOException {
   // COMPLETE THIS METHOD
}
 <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper); 

Stream#flatMap映射器期望返回Stream 你正在返回一個String[] 要將String[]轉換為Stream<String> ,請使用Arrays.stream(a.split(" "))

完成答案的完整答案:

public static Map<Integer, List<String>> wordsByLength(String file)
        throws IOException {
    return Files.lines(Paths.get(file))
                .flatMap(a -> Arrays.stream(a.split("\\s+")))
                .collect(Collectors.groupingBy(String::length));
}

傳遞給flatMap的函數必須返回流,而不是數組。

例如

.flatMap(a -> Arrays.stream(a.split(" ")))

你需要.flatMap()操作:

  • 正常的.map()操作之后

     Files.lines(Paths.get(file)).map(a -> a.split(" ")).flatMap(Arrays::stream); 
  • 結合法線map操作:

     Files.lines(Paths.get(file)).flatMap(a -> Arrays.stream(a.split(" "))); 

最后你需要

public static Map<Integer, List<String>> wordsByLength(String file) throws IOException {
    return Files.lines(Paths.get(file))                      //Stream<String>
            .map(a -> a.split(" "))                          //Stream<String[]>
            .flatMap(Arrays::stream)                         //Stream<String>
            .collect(Collectors.groupingBy(String::length)); //Map<Integer, List<String>>
}

暫無
暫無

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

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