0

次のコードを使用してハッシュマップを作成し、ツリーマップとコンパレータを使用してハッシュマップ内の値を並べ替えます。ただし、出力はかなり予期しないものです。だから、私が間違っていることについての考えは役に立ちます

コード

public static void main(String[] args) {
    System.out.println("Most freq"+mostFreq(" i me hello hello hello me"));
}


public static String[] mostFreq(String str){

    if ((str==null)||( str.trim().equalsIgnoreCase("")))
        return null;

    String[] arr = new String[10];

    String[] words= str.split(" ");

    Map <String,Integer> map = new HashMap<String,Integer>();

    for (String word :words)
    { 
        int count =0;
        if (map.containsKey(word))
        {     
            count= map.get(word);
            map.put(word, count+1);
        }             
        else
            map.put(word, 1);
    }

    MyComparator comp= new MyComparator(map);
    Map<String,Integer> newMap= new TreeMap(comp);
    newMap.putAll(map);
    Iterator it= newMap.entrySet().iterator();
    while (it.hasNext())
    {
        Map.Entry pairs = (Map.Entry) it.next();
        System.out.println("Key  "+pairs.getKey()+"-- value"+pairs.getValue());
    }

    return arr;
}

比較対象はこちら

package samplecodes;

import java.util.Comparator;
import java.util.Map;

public class MyComparator implements Comparator {

    Map map;

    public MyComparator(Map map){
        this.map=map;
    }

    @Override
    public int compare(Object o1, Object o2) {
        return ((Integer)map.get(o1) >(Integer)map.get(o2)? (Integer)map.get(o1):(Integer)map.get(o2));
    }

}

そして、出力は次の形式です

me-2
hello-3
i-3
4

3 に答える 3

3

の JavaDoc を確認してください: より大きな値を返すのではcompareなく-1o1< o2、 =および>の場合。したがって、次のように書くことができます。0o1o21o1o2

@Override
public int compare(Object o1, Object o2) {
    return ((Integer) map.get(o1)).compareTo((Integer) map.get(o2);
}
于 2013-10-25T02:14:03.847 に答える
0

あなたがしていることは、本当にツールの誤用です。

あなたがする必要があるのは次のことだと思います:

  1. 入力単語のリスト/配列を持っています(入力文字列を分割して取得しても問題ありません)
  2. 単語をキーとして格納し、頻度を値として格納するマップを作成します
  3. ユニークな単語のコレクションを作成し、頻度に基づいてコレクションを並べ替えます
  4. 出力を行うときは、ソートされた一意の単語リストをトラバースし、要素ごとに、frequencyMap から頻度を取得し、単語 + 頻度を出力します。

もちろん、TreeSet のようなものを使用して頻度をキーとして使用することもできますが、コントラクトに従わない問題のあるコンパレーターを記述する代わりに、このマップ (別名マルチマップ) の値として単語のリストを使用する必要があります。 Comparator の: http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html#compare%28T,%20T%29 元の実装と、回答はのルールに準拠していませんsgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y (元の回答はさらに悪いです)。

ヒントを提供するためだけのコード スニペット:

List<String> words = ....;
Map<String, Integer> wordFrequencyMap = new HashMap<String, Integer>();
// iterate words and update wordFrequencyMap accordingly
List<String> uniqueWords = new ArrayList<String>(new HashSet<String>(words));
Collections.sort(uniqueWords, new WordFrequencyComparator<String>(wordFrequencyMap));
for (String w : uniqueWords) {
  System.out.println("word : " + w + "  frequency : " + wordFrequencyMap.get(w));
}

欠けている部分は難しいことではありません。

于 2013-10-25T03:21:38.953 に答える