2012-09-01 13 views
7
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); 

Come posso restituire un numero di quante persone ha il valorecontare quante voci HashMap hanno un dato valore

+0

Questo è Java, giusto? – alfasin

+3

Iterate la raccolta * values ​​* e confrontate ciascun valore con '1'. – adatapost

+0

È possibile eseguire java, Iterate. Forse c'era un altro modo. – user1621988

risposta

3

Prova questo:

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); 
+1

Perché si modifica 'partito' utilizzando' Iterator.remove'? Questa informazione potrebbe essere necessaria in seguito. –

+0

In che modo * eviti * "ConcurrentModificationException' di * modificando * la struttura? –

+0

Non ho idea di cosa tu stia parlando: P – alfasin

2

è possibile utilizzare questo

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()); 
} 
14

Vorrei usare il Colle metodo ctions.frequency() sui valori HashMap, come questo.

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

Oppure la soluzione generale, generare una mappa di frequenza in base al numero.

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} 
+0

+1 la tua soluzione è migliore! – alfasin

+0

mi piace anche a me ... – ycomp

2

Prova questa libreria per un sacco di tale gruppo in base alla funzione 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()); 

Potrebbe essere necessario importare queste dipendenze Maven

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

e hamcrest matchers per

equalTo(1) 
Problemi correlati