Indicate how many HashMap entries have a given value.

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

How can I return a number , how many people matter 1

+7
source share
4 answers

I would use the Collections.frequency () method for HashMap values, for example.

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

Or a general solution, generate a frequency map versus a number.

 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} 
+14
source

Try the following:

 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); 
+3
source

you can use this

 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()); } 
+2
source

Try this library for many of these feature groups at 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()); 

You may need to import these maven dependencies

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

and hamcrest for

 equalTo(1) 
+2
source

All Articles