需要对文件中的单词按照出现次数和确定符号进行排序(先按出现次数排序,再按字母排序)。例如,对于符号“e”,结果应为:avrgspeed=2;变成=2;因为=2 ...自动=1;自动连线=1。
有没有更好的方法来以流式编写所有内容。
public class Sorter {
public Map<String, Integer> getDistinctWordsMap(String path, char symbol) throws IOException {
Pattern delimeter = Pattern.compile("([^a-zA-Z])");
List<WordParameter> parameterList = new ArrayList<>();
Files.lines(Paths.get(path))
.flatMap(delimeter::splitAsStream).map(String::toLowerCase).distinct()
.forEachOrdered(word -> parameterList.add(new WordParameter(word, symbol)));
Collections.sort(parameterList);
return parameterList.stream().filter(w->w.count>0).collect(toMap(n->n.word, n->n.count, (e1, e2) -> e1, LinkedHashMap::new));
}
class WordParameter implements Comparable<WordParameter>{
String word;
int count;
public WordParameter(String word, char symbol) {
this.word = word;
this.count = countEntrance(symbol);
}
private int countEntrance(char symbol){
int quantity = 0;
char[] charArr = word.toCharArray();
for(int i = 0; …Run Code Online (Sandbox Code Playgroud) 需要从文件中返回包含3个或更多单词的所有单词的流.是否有更好的方式,然后使用Stream.iterate:
private Stream<String> getWordsStream(String path){
Stream.Builder<String> wordsStream = Stream.builder();
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(path);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Scanner s = new Scanner(inputStream);
s.useDelimiter("([^a-zA-Z])");
Pattern pattern = Pattern.compile("([a-zA-Z]{3,})");
while ((s.hasNext())){
if(s.hasNext(pattern)){
wordsStream.add(s.next().toUpperCase());
}
else {
s.next();
}
}
s.close();
return wordsStream.build();
}
Run Code Online (Sandbox Code Playgroud)