0
public class nrlSports {
    public static void main(String[] args){
        String[] direction = {"north", "north", "east", "south", "south", "south", "north", "north"};

        for(int i=0; i<direction.length; i++) {
            int count = 0;
            for(int j = 0; j < direction.length; j++)
                if(direction[i].equals(direction[j])) {
                    count++;
                }
            System.out.println(direction[i] + " (" + count + ")");
        }
    }
}

出力は次のとおりです。北 (4) 北 (4) 東 (1) 南 (3) 南 (3) 南 (3) 北 (4) 北 (4)

これらの重複した値を削除して、出力が次のようになるようにするにはどうすればよいですか: 北 (4) 東 (1) 南 (3)

4

5 に答える 5

1

これは役立ちます:

public static void main(String[] args){
    String[] direction = {"north", "north", "east", "south", 
                          "south", "south", "north", "north"};
    Map<String, Integer> countMap = new HashMap<String, Integer>();

    for(int i=0; i<direction.length; i++) {
        String key = direction[i];
        if(!countMap.containsKey(key)){
            countMap.put(key, 1);
        }
        else 
        {
            countMap.put(key, countMap.get(key)+1);
        }
    }
    System.out.println(countMap);
}
于 2013-04-17T15:37:12.300 に答える
0

セットを使用します。それらすべてをセットに追加すると、一意の値が得られます。

編集:カウント部分を逃しました。今すぐ追加

String[] direction = {"north", "north", "east", "south", 
                          "south", "south", "north", "north"};

    Map<String,int> m = new HashMap<String,int>();

 for(String str:direction){
    if(m.contains(str))
       m.put(key,m.get(str)+1);
    else
       m.put(key,1);
}


//key is all values you want to add and count in no. of times values is repeated.

したがって、すべての一意の値が必要な場合は、キーセットを反復処理して、マップから対応するカウントを取得できます。

于 2013-04-17T15:29:19.757 に答える
0

私の可能な簡単な方法は

Set<String> directionS= new HashSet<String>(Arrays.asList(direction));

そして遊ぶ directionS

于 2013-04-17T15:30:31.540 に答える