16
public final static HashMap<String, Integer> party = new HashMap<String, Integer>();
party.put("Jan",1);
party.put("John",1);
party.put("Brian",1);
party.put("Dave",1);
party.put("David",2);

値が1の人の数を返すにはどうすればよいですか

4

5 に答える 5

28

このように、HashMap 値に対して Collections.frequency() メソッドを使用するだけです。

int count = Collections.frequency(party.values(), 1);
System.out.println(count);
===> 4

または、一般的な解決策として、頻度と数のマップを生成します。

Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
for (Integer c : party.values()) {
    int value = counts.get(c) == null ? 0 : counts.get(c);
    counts.put(c, value + 1);
}
System.out.println(counts);
==> {1=4, 2=1}
于 2012-09-01T08:29:00.547 に答える
3

これを試して:

int counter = 0;
Iterator it = party.entrySet().iterator();
while (it.hasNext()) {
  Map.Entry pairs = (Map.Entry)it.next();
  if(pairs.getValue() == 1){
    counter++; 
  }      
}
System.out.println("number of 1's: "+counter);
于 2012-09-01T08:22:59.103 に答える
2

あなたはこれを使うことができます

HashMap<String, Integer> party = new HashMap<String, Integer>();
party.put("Jan",1);
party.put("John",1);
party.put("Brian",1);
party.put("Dave",1);
party.put("David",2);

Set<Entry<String, Integer>> set = party.entrySet();
for (Entry<String, Integer> me : set) {
    if(me.getValue()==1)
    System.out.println(me.getKey() + " : " + me.getValue());
}
于 2012-09-01T08:23:28.973 に答える
2

関数ごとにこのようなグループの多くについてこのライブラリを試してみて ください http://code.google.com/p/lambdaj/wiki/LambdajFeatures

HashMap<String, Integer> party = new HashMap<String, Integer>();
    party.put("Jan",1);
    party.put("John",1);
    party.put("Brian",1);
    party.put("Dave",1);
    party.put("David",2);
    List<Integer> list = filter(equalTo(1),party.values());
    System.out.println(list.size());

これらの Maven 依存関係をインポートする必要がある場合があります

<dependency>
      <groupId>com.googlecode.lambdaj</groupId>
     <artifactId>lambdaj</artifactId>
    <version>2.3.3</version>

ハムクレストマッチャー

equalTo(1)
于 2012-09-01T09:07:43.653 に答える