圣经独特的单词计数器瓶颈

时间:2019-03-30 05:09:36

标签: java java.util.scanner

我们假设要创建一个程序,该程序对在《詹姆斯国王圣经》的文本文件中找到的所有唯一单词进行计数,并打印出最常用的单词。我计算唯一单词数量的功能太慢了:

public int parseBook(File fileName) throws FileNotFoundException {

    scan = new Scanner(fileName);
    String currentWord = scan.next();
    Word firstWord = new Word(currentWord);
    allWords.add(firstWord);
    wordCount++;
    while(scan.hasNext()) {
        currentWord = scan.next();
            Word newWord = new Word(currentWord);
            if(!allWords.contains(newWord)) {
                uniquewordList.add(newWord);


            }

            else {
                newWord.incrementFrequency();
            }
            allWords.add(newWord);

    }
    return uniquewordList.size();
}

1 个答案:

答案 0 :(得分:0)

这很简单。只需使用 public class Client extends AsyncTask<String, Integer, Boolean> { Socket socket; String hostAdd; InputStream inputStream; OutputStream outputStream; public Client(InetAddress hostAddress) { hostAdd = hostAddress.getHostAddress(); socket = new Socket(); } @Override protected Boolean doInBackground(String... strings) { boolean result = false; try { socket.connect(new InetSocketAddress(hostAdd, 8888), 5000); result = true; return result; } catch (IOException e) { e.printStackTrace(); result = false; return result; } } public void writeData(final byte[] bytes) { new Thread(new Runnable() { @Override public void run() { try { outputStream.write(bytes); } catch (IOException e) { e.printStackTrace(); } } }).start(); btnSend.setVisibility(View.VISIBLE); } @Override protected void onPostExecute(Boolean result) { if(result) { try { inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } new Thread(new Runnable(){ public void run() { byte[] buffer = new byte[1024]; int x; while (socket!=null) { try { x = inputStream.read(buffer); if(x>0) { handler.obtainMessage(MESSAGE_READ,x,-1,buffer).sendToTarget(); } } catch (IOException e) { e.printStackTrace(); } } } }).start(); btnSend.setVisibility(View.VISIBLE); } else { Toast.makeText(getApplicationContext(),"could not create sockets",Toast.LENGTH_SHORT).show(); //restart socket assignment process } } } 并输入所有单词即可。将 O(1)插入一个单词到Set中。

Set