【发布时间】:2017-02-19 14:11:29
【问题描述】:
这是我读取两个文件的代码,一个带有单词,另一个带有乱码。程序读取乱码字母并将其与文件中的单词进行匹配。它有效,但我希望输出按字母顺序排列。我可以在代码的哪个位置进行排序?
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[]) throws Exception
{
BufferedReader dictionary = new BufferedReader( new FileReader(args[0]) );
BufferedReader jumbles = new BufferedReader( new FileReader(args[1]) );
HashMap<String, List<String>> lookup = new HashMap<String, List<String>>();
while(dictionary.ready())
{
String word = dictionary.readLine();
addWord(word, lookup);
}
dictionary.close();
while(jumbles.ready())
{
String jWord = jumbles.readLine();
List<String>dWords= lookup.get(createKey(jWord));
String wordsString = Arrays.toString(dWords.toArray()).replace("[", "").replace("]", "").replace(",", "").trim();
if(dWords != null){
System.out.println(jWord + " " + wordsString);
}
}
jumbles.close();
}
private static String createKey(String word)
{
char[] cword = word.toCharArray();
Arrays.sort(cword);
return new String(cword);
}
private static void addWord(String word, Map<String, List<String>> lookup)
{
String key = createKey(word);
List<String> list = lookup.get(key);
if(list == null)
{
list = new ArrayList<String>();
lookup.put(key, list);
}
list.add(word);
}
}
输出:
atc act cat tac
otsp post pots stop spot tops opts
gdo dog god
atr rat tar art
arpt trap tarp part
grof frog
sylogs glossy
我想要什么:
arpt part tarp trap
atc act cat tac
atr art rat tar
gdo dog god
grof frog
otsp opts post pots spot stop tops
sylogs glossy
没关系。
修复它:
while(jumbles.ready())
{
jSorted.add(jumbles.readLine());
}
jumbles.close();
Collections.sort(jSorted);
for(int i = 0; i < jSorted.size(); i++)
{
String jWord = jSorted.get(i);
List<String>dWords= lookup.get(createKey(jWord));
String wordsString = Arrays.toString(dWords.toArray()).replace("[", "").replace("]", "").replace(",", "").trim();
if(dWords != null){
System.out.println(jWord + " " + wordsString);
}
}
【问题讨论】:
-
请使用 TreeMap 而不是 HashMap 进行检查。
-
您的输入文件似乎没有按字母顺序排列,但您想按字母顺序处理单词。读取文件并创建
ArrayList,然后对ArrayList进行排序,然后处理文件中的单词。 -
@CS_noob 这无济于事。他想要排序的不是字典输入。这个问题根本不是关于
HashMap,尽管有标题。