【发布时间】:2019-04-29 22:52:27
【问题描述】:
需要对文件中的单词按入口数量和确定符号进行排序(先按入口数量排序,再按字母排序)。例如,对于符号 '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; i<charArr.length; i++){
if(charArr[i]==symbol){
quantity++;
}
}
return quantity;
}
@Override
public int compareTo(WordParameter o) {
if(count<o.count)
return 1;
else if(count>o.count)
return -1;
else {
return word.compareTo(o.word);
}
}
}
}
【问题讨论】:
-
返回类型必须是map、set或list
标签: java sorting dictionary key java-stream