a_c*_*nko 2 java sorting dictionary key java-stream
需要对文件中的单词按照出现次数和确定符号进行排序(先按出现次数排序,再按字母排序)。例如,对于符号“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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
}
您绝对可以减少样板代码并使其更加简洁。
\n\n没有测试下面的代码,但是像这样的东西应该足够了:
Files.lines(Paths.get(path))\n .flatMap(delimeter::splitAsStream)\n .map(String::toLowerCase)\n .filter(s -> s.indexOf(symbol) >= 0)\n .distinct()\n .map(s -> new SimpleEntry<>(s, s.chars().filter(c -> c == symbol).count()))\n .sorted(Map.Entry.<String,Long>comparingByValue(Comparator.reverseOrder())\n .thenComparing(Map.Entry::getKey))\n .collect(toMap(SimpleEntry::getKey, e -> e.getValue().intValue(), (l, r) -> l, LinkedHashMap::new));\nRun Code Online (Sandbox Code Playgroud)\n\n这意味着您不再需要您的自定义类,因为我们\xe2\x80\x99正在使用SimpleEntry这意味着您不再需要您的自定义类,因为我们在流管道中