我擁有的內容:逐行讀取的文本文件。每個字符串都包含一行。按第一個字符分組的單詞
我想要的:使用Java Streams按第一個字符對所有單詞進行分組。
我到目前爲止有:
public static Map<Character, List<String>> groupByFirstChar(String fileName)
throws IOException {
return Files.lines(Paths.get(PATH)).
flatMap(s -> Stream.of(s.split("[^a-zA-Z]"))).
map(s -> s.toLowerCase()).
sorted((s1, s2) -> s1.compareTo(s2)).
collect(Collectors.groupingBy(s -> s.charAt(0)));
}
問題:我得到一個異常
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:646)
at textana.TextAnalysisFns.lambda$16(TextAnalysisFns.java:110)
at textana.TextAnalysisFns$$Lambda$36/159413332.apply(Unknown Source)
at java.util.stream.Collectors.lambda$groupingBy$196(Collectors.java:907)
at java.util.stream.Collectors$$Lambda$23/189568618.accept(Unknown Source)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.stream.SortedOps$RefSortingSink$$Lambda$37/186370029.accept(Unknown Source)
at java.util.ArrayList.forEach(ArrayList.java:1249)
at java.util.stream.SortedOps$RefSortingSink.end(SortedOps.java:390)
at java.util.stream.Sink$ChainedReference.end(Sink.java:258)
at java.util.stream.Sink$ChainedReference.end(Sink.java:258)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:513)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at textana.TextAnalysisFns.groupByFirstChar(TextAnalysisFns.java:110)
at textana.SampleTextAnalysisApp.main(SampleTextAnalysisApp.java:95)
問題:爲什麼我得到一個StringIndexOutOfBoundException?
解決方案基於評論提示:
public static Map<Character, List<String>> groupByFirstChar(String fileName)
throws IOException {
return Files.lines(Paths.get(PATH)).
flatMap(s -> Stream.of(s.split("[^a-zA-Z]"))).
filter(s -> s.length() > 0).
map(s -> s.toLowerCase()).
collect(Collectors.groupingBy(s -> s.charAt(0)));
}
用戶葉蘭的解決方案還必須給我在我不想有開頭空字符串。
順便說一句,你可以跳過排序()操作的參數,因爲你是使用自然順序。 –