2017-03-29 13 views
0

私はファイル内に1000個の文を含むファイルを解析する必要があります。 ファイル内でユニークな単語を見つけなければならないということは、ファイル内で一度も来ていないことを意味します。 これ、私が使用する必要があるのデータ構造。(JavaのみのDSを使用して、この操作を実行する必要がある)と、なぜ、どのように適切なjavaのデータ構造ファイルからユニークな単語を見つける

第二の質問は

map.put("abc","hello"); 
map.put.("ABC","hi"); 

コード上で与えたとして、我々はマップオブジェクトに挿入されています何が起こるか。

答えて

0

あなたはマップの魔女の中にあなたの言葉を記入することができますキーを単語と値の発生数。
マップループでデータをもう一度入力し終わったら、値が大きいか等しいかを再度確認し、大きい場合はマップから削除します。 そして、あなたはあなただけabcまたはABCを使用したくない場合は、挿入したとき、あなたはLowerCaseUpperCaseを使用したCA ユニークワード


の数を知ることが、最終的にこのマップのサイズを返すことができますあなたの地図で。ここで

あなたが投げる行くことができ、簡単な例は:

public static void main(String[] args) { 
    //i consider you know how to learn from a file, i use a simple array just to explain 
    String[] listWords = {"hello", "word", "hello", "stack", "HELLO", "WORD", "123", "what?"}; 

    //fill your words in your map 
    Map<String, Integer> map = new HashMap<>(); 
    for (String word : listWords) { 
     if (!map.containsKey(word.toLowerCase())) { 
      map.put(word.toLowerCase(), 1); 
     } else { 
      map.put(word.toLowerCase(), map.get(word.toLowerCase()) + 1); 
     } 
    } 

    //print your map 
    map.entrySet().forEach((entry) -> { 
     System.out.println("word : " + entry.getKey() + " occurence : " + entry.getValue()); 
    }); 
    System.out.println("**************************************************"); 
    //loop throw your map and remove the words which occurrence > 1 
    for (Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator(); it.hasNext();) { 
     Map.Entry<String, Integer> entry = it.next(); 
     if (entry.getValue() > 1) { 
      it.remove(); 
     } 
    } 

    //print your map again 
    map.entrySet().forEach((entry) -> { 
     System.out.println("word : " + entry.getKey() + " occurence : " + entry.getValue()); 
    }); 

    //size of your end map 
    System.out.println("Size of map = " + map.size()); 
} 

あなたがマップでプレイするものをベースにすることができますいくつかの良い参考文献:

How to update a value, given a key in a java hashmap?
iterating over and removing from a map

・ホープ、このあなたにアイデアを与えることができます。

0

マップを使用して、地図に置いた単語ごとに単語をキーと値として使用し、カウントを1増加させます。

if(map.containsKey("some")){ 
    // get the current value 
    int currentValue = map.get("some"); 
    // put back the key with incremented value 
    map.put("some",currentValue+1); 
} else { 
    // first time 
    map.put("some",1); 
} 

2番目の質問では、地図キーに大文字と小文字が区別されるため、両方のputがマップに追加されます。

+0

ありがとうございました。 –

関連する問題