2011-05-01 5 views
2

해시 맵을 사용하여 파일의 여러 문자열 발생 횟수를 계산하려고합니다. 이 일을 어떻게 하죠? 또한 비슷한 방식으로 고유 한 문자열의 수를 계산할 수 있습니까? 예를 들어 주시면 감사하겠습니다.Java Hashmap 구현

답변

6

예를 들어 파일에서 단어를 읽고 Java 키워드가 몇 번이나 나왔는지 계산하는 프로그램이 있습니다.

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.Map; 
import java.util.HashMap; 

public class CountKeywords { 

    public static void main(String args[]) { 

     String[] theKeywords = { "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while" }; 

     // put each keyword in the map with value 0 
     Map<String, Integer> theKeywordCount = new HashMap<String, Integer>(); 
     for (String str : theKeywords) { 
      theKeywordCount.put(str, 0); 
     } 

     FileReader fr; 
     BufferedReader br; 
     File file = new File(args[0]); // the filename is passed in as a String 

     // attempt to open and read file 
     try { 
      fr = new FileReader(file); 
      br = new BufferedReader(fr); 

      String sLine; 

      // read lines until reaching the end of the file 
      while ((sLine = br.readLine()) != null) { 

       // if an empty line was read 
       if (sLine.length() != 0) { 

        // extract the words from the current line in the file 
        if (theKeywordCount.containsKey(sLine)) { 
         theKeywordCount.put(sLine, theKeywordCount.get(sLine) + 1); 
        } 
       } 
      } 

     } catch (FileNotFoundException exception) { 
      // Unable to find file. 
      exception.printStackTrace(); 
     } catch (IOException exception) { 
      // Unable to read line. 
      exception.printStackTrace(); 
     } finally { 
       br.close(); 
      } 

     // count how many times each keyword was encontered 
     int occurrences = 0; 
     for (Integer i : theKeywordCount.values()) { 
      occurrences += i; 
     } 

     System.out.println("\n\nTotal occurences in file: " + occurrences); 
    } 
} 

고유 한 문자열에 대한 질문에 대답하려면 비슷한 방식으로 HashMap을 사용하는 방식을 적용 할 수 있습니다.

  1. 새의 HashMap를 작성, 호출 uniqueStrings
  2. 파일에서 문자열을 읽을 때 그렇지, 다음 추가 않을 경우 횟수를 추적 HashMap의 현재 문자열을
    • 이 포함되어 있는지 확인 그것은 않는 경우 파일을 읽는 완료 후 uniqueStrings
    • 로는, 다음 uniqueStrings
  3. 에서 제거, 당신은 단지 고유의 것 문자열이 uniqueStrings

질문이 있으시면 알려주세요.

이 정보가 도움이되기를 바랍니다.
Hristo

+0

감사합니다. 매우 도움이됩니다. 그들은 또한 파일에서, StringTokenizer를 사용하여 다음 HashMap 작업에 추가 할 키워드입니까? 나는 독특한 끈에 대한 가난한 표현을 사용했다. 내가해야 할 일은 로그 파일에있는 고유 한 IP 주소의 수를 세는 것입니다. 또는 HashMap에 이미있는 경우 HashMap에 추가했는지 확인하고, 추가하지 않으면 다시 추가합니다. 마지막으로 HashMap에있는 IP 주소의 수를 세십시오. – Terezi

+0

고마워. 고맙습니다. :) – Terezi

+0

@Terezi ... 도울 수있어서 기뻐요. – Hristo

0

고유 한 문자열을 추적하기 위해 파일에서 발생 횟수를 추적 할 필요가 없습니다. 대신, 코드 명확성을 위해 HashMap 대신 HashSet을 사용할 수 있습니다.

참고 : HashSet은 내부적으로 HashMap으로 백업되며 키 값 쌍의 값으로 사용됩니다.

+1

그래,하지만 세트에는 모든 고유 문자열 만 있고, OP는 각 고유 문자열의 출현을 계산하기를 원했습니다. 세트로 어떻게 할 것을 제안합니까? – sharakan