I'm trying to sort a HashMap in two ways. The default way: alphabetically by the value, the second way: numerically by the key, with the higher number being at the top. I have searched around but can't find anything on the subject, and what I do find, doesn't work. If it's not possible to sort both of them (I want the person with the highest key at the top, decreasing as people have lower keys, then alphabetically sort all of the rest (the people with 0 as their key).
Here's what I've tried so far:
private HashMap<String, Integer> userGains = new HashMap<String, Integer>();
public void sortGains(int skill, int user) {
userGains.put(users.get(user).getUsername(), users.get(user).getGainedExperience(skill));
HashMap<String, Integer> map = sortHashMap(userGains);
for (int i = 0; i < map.size(); i++) {
Application.getTrackerOutput().getOutputArea(skill).append(users.get(user).getUsername() + " gained " + map.get(users.get(user).getUsername()) + " experience in " + getSkillName(skill) + ".\n");
}
}
public LinkedHashMap<String, Integer> sortHashMap(HashMap<String, Integer> passedMap) {
List<String> mapKeys = new ArrayList<String>(passedMap.keySet());
List<Integer> mapValues = new ArrayList<Integer>(passedMap.values());
LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
Collections.sort(mapValues);
Collections.sort(mapKeys);
Iterator<Integer> it$ = mapValues.iterator();
while (it$.hasNext()) {
Object val = it$.next();
Iterator<String> keyIt = mapKeys.iterator();
while (keyIt.hasNext()) {
Object key = keyIt.next();
String comp1 = passedMap.get(key).toString();
String comp2 = val.toString();
if (comp1.equals(comp2)) {
passedMap.remove(key);
mapKeys.remove(key);
sortedMap.put((String) key, (Integer) val);
break;
}
}
}
return sortedMap;
}
Since you cannot run that here is an SSCCE:
private HashMap<String, Integer> userGains = new HashMap<String, Integer>();
private Object[][] testUsers = { { "Test user", 15 }, { "Test", 25 }, { "Hello", 11 }, { "I'm a user", 21 }, { "No you're not!", 14 }, { "Yes I am!", 45 }, { "Oh, okay. Sorry about the confusion.", 0 }, { "It's quite alright.", 0 } };
public static void main(String[] arguments) {
new Sorting().sortGains();
}
public void sortGains() {
for (Object[] test : testUsers) {
userGains.put((String) test[0], (Integer) test[1]);
}
HashMap<String, Integer> map = sortHashMap(userGains);
for (int i = 0; i < map.size(); i++) {
System.out.println(testUsers[i][0] + " gained " + map.get(testUsers[i][0]) + " experience.");
}
}
public LinkedHashMap<String, Integer> sortHashMap(HashMap<String, Integer> passedMap) {
List<String> mapKeys = new ArrayList<String>(passedMap.keySet());
List<Integer> mapValues = new ArrayList<Integer>(passedMap.values());
LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
Collections.sort(mapValues);
Collections.sort(mapKeys);
Iterator<Integer> it$ = mapValues.iterator();
while (it$.hasNext()) {
Object val = it$.next();
Iterator<String> keyIt = mapKeys.iterator();
while (keyIt.hasNext()) {
Object key = keyIt.next();
String comp1 = passedMap.get(key).toString();
String comp2 = val.toString();
if (comp1.equals(comp2)) {
passedMap.remove(key);
mapKeys.remove(key);
sortedMap.put((String) key, (Integer) val);
break;
}
}
}
return sortedMap;
}
The output of the program is currently:
Test user gained 15 experience.
Test gained 25 experience.
Hello gained 11 experience.
I'm a user gained 21 experience.
No you're not! gained 14 experience.
Yes I am! gained 45 experience.
Oh, okay. Sorry about the confusion. gained 0 experience.
It's quite alright. gained 0 experience.
When I need it to be:
Yes I am! gained 45 experience. // start numeric sorting here, by highest key.
Test gained 25 experience.
I'm a user gained 21 experience.
Test user gained 15 experience.
No you're not! gained 14 experience.
Hello gained 11 experience.
It's quite alright. gained 0 experience. // start alphabetical sorting here, if possible.
Oh, okay. Sorry about the confusion. gained 0 experience.
Any insight?
It's not possible to sort a HashMap at all. By definition, the keys in a HashMap are unordered. If you want the keys of your Map to be ordered, then use a TreeMap with an appropriate Comparator object. You can create multiple TreeMaps with different Comparators if you want to access the same data multiple ways.
You made a mistake in displaying the values.
HashMap<String, Integer> map = sortHashMap(userGains);
for (int i = 0; i < map.size(); i++) {
System.out.println(testUsers[i][0] + " gained " + map.get(testUsers[i][0]) + " experience.");
}
You need to display the map's values instead of the original array's values.
This should do:
HashMap<String, Integer> map = sortHashMap(userGains);
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " gained " + entry.getValue() + " experience.");
}
You only have to reverse the order. Further I recommend to declare against Map instead of HashMap or LinkedHashMap to avoid confusion by yourself and others. Also your sorting can simpler be done with a Comparable. Here's an improvement:
private Map<String, Integer> userGains = new HashMap<String, Integer>();
private Object[][] testUsers = { { "Test user", 15 }, { "Test", 25 }, { "Hello", 11 }, { "I'm a user", 21 }, { "No you're not!", 14 }, { "Yes I am!", 45 }, { "Oh, okay. Sorry about the confusion.", 0 }, { "It's quite alright.", 0 } };
public static void main(String[] arguments) {
new Sorting().sortGains();
}
public void sortGains() {
for (Object[] test : testUsers) {
userGains.put((String) test[0], (Integer) test[1]);
}
Map<String, Integer> map = createSortedMap(userGains);
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " gained " + entry.getValue() + " experience.");
}
}
public Map<String, Integer> createSortedMap(Map<String, Integer> passedMap) {
List<Entry<String, Integer>> entryList = new ArrayList<Entry<String, Integer>>(passedMap.entrySet());
Collections.sort(entryList, new Comparator<Entry<String, Integer>>() {
#Override
public int compare(Entry<String, Integer> e1, Entry<String, Integer> e2) {
if (!e1.getValue().equals(e2.getValue())) {
return e1.getValue().compareTo(e2.getValue()) * -1; // The * -1 reverses the order.
} else {
return e1.getKey().compareTo(e2.getKey());
}
}
});
Map<String, Integer> orderedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : entryList) {
orderedMap.put(entry.getKey(), entry.getValue());
}
return orderedMap;
}
This question approaches what you're trying to do, by sorting on value in a TreeMap. If you take the most voted answer and modify the Comparator to sort on value then key, it should give you what you want.
Effectively, you create a Comparator that has a field that points to the TreeMap (so it can look up values). And the TreeMap uses this Comparator. When items are added to the TreeMap, the Comparator looks up the values and does a comparison on
if the value a < value b, return 1
if the value a > value b, return -1
if the key a < key b, return 1
if the key a > key b, return -1
otherwise, return 0
Copying a lot of code from that answer (with no checking to see if the code works, since it's just for the idea):
public class Main {
public static void main(String[] args) {
ValueComparator<String> bvc = new ValueComparator<String>();
TreeMap<String,Integer> sorted_map = new TreeMap<String,Integer>(bvc);
bvc.setBase(sorted_map);
// add items
// ....
System.out.println("results");
for (String key : sorted_map.keySet()) {
System.out.println("key/value: " + key + "/"+sorted_map.get(key));
}
}
}
class ValueComparator implements Comparator<String> {
Map base;
public setBase(Map<String,Integer> base) {
this.base = base;
}
public int compare(String a, String b) {
Integer value_a = base.get(a);
Integer value_b = base.get(b);
if(value_a < value_b) {
return 1;
}
if(value_a>< value_b) {
return -1;
}
return a.compareTo(b);
}
}
Related
I'm trying to sort a HashMap<String, Long>. I'm have the following code for sorting:
private static class ValueComparator implements Comparator<String>{
HashMap<String, Long> map = new HashMap<String, Long>();
public ValueComparator(HashMap<String, Long> map){
this.map.putAll(map);
}
#Override
public int compare(String s1, String s2) {
if(map.get(s1) > map.get(s2)){
System.out.println("s1: " + s1 + "; s2: " + s2);
return -1;
}
else if (map.get(s1).equals(map.get(s2))) {
return 0;
}
else{
return 1;
}
}
}
private static TreeMap<String, Long> sortMapByValue(HashMap<String, Long> map){
Comparator<String> comparator = new ValueComparator(map);
//TreeMap is a map sorted by its keys.
//The comparator is used to sort the TreeMap by keys.
TreeMap<String, Long> result = new TreeMap<String, Long>(comparator);
result.putAll(map);
System.out.println("DONE sort");
return result;
}
The problem is, when several different keys have the same values, only one of the key makes it into the final map:
EXAMPLE:
public class Test {
public static void main(String[] args) {
HashMap<String, Long> hashMap = new HashMap<>();
hashMap.put("Cat", (long) 4);
hashMap.put("Human", (long) 2);
hashMap.put("Dog", (long) 4);
hashMap.put("Fish", (long) 0);
hashMap.put("Tree", (long) 1);
hashMap.put("Three-legged-human", (long) 3);
hashMap.put("Monkey", (long) 2);
System.out.println(hashMap); //7 pairs
System.out.println(sortMapByValue(hashMap)); //5 pairs
}
}
How would I fix it?
I don't think it's fixable you are using the the maps in an unintended way and breaking contracts. Tree map is expecting to be sorted by the key and the key is expected to be unique so when the compare == 0 it will just override the node's value. You can always implement your own TreeMap and make it do whatever you want it to.
I'm not sure what you want to do with it but I think you need something like
TreeMap<Long,List<String>>
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/TreeMap.java
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
I have 2 Arraylists in my app. First arraylist is of Object type which contains a list of questions. Now this list of questions have a field named "Keywords". This is a String but can contain comma separated keywords.
Now I have a text field where user can search question based on these keywords.Issue that I am facing is that I want to filter out question from the question list according to the number of keyword matches.
For eg. User entered 3 comma separated keywords in the search text field. What I want now is if all 3 keyword matches with some value in the question list then I have to return those elements only. This part is easy and I can do it.
But if we don't get any exact match in the list, then I have to find that item which has the maximum keyword match i.e. if 2 out of 3 keywords from the comma separated String matches from some item in the list, then I have to return that item as result.
Value Stored in List :-
a) Hi, Hello, Hola, Bonjour.
b) Hi, Hello
c) Hi
Value entered in the search text :-
Hi, Hello, Hola
Now in response I want only the first element as it has 3 keywords matching from what user entered.
I am unable to figure out how to do this. Moreover I am fetching this questions list from sqlite database, so if this can be done with some sql queries then I am ready for that thing too.
This is my current code for filter method
public ArrayList<QuestionAnswerModal> filter(String keyword,boolean isQuestionSearch) {
ArrayList<QuestionAnswerModal> arrayList = new ArrayList<>();
if (!isQuestionSearch) {
for (QuestionAnswerModal modal : questionAnswerArrayList) {
if (modal.getKeyword().equalsIgnoreCase(keyword)) {
arrayList.add(modal);
}else{
ArrayList<String> keywords=new ArrayList<>();
String[]word=modal.getKeyword().split(",");
}
}
if (arrayList.size() > 0) {
System.out.print("list size "+arrayList.size());
} else {
System.out.print("No records found");
}
return arrayList;
}else{
for (QuestionAnswerModal modal : questionAnswerArrayList) {
if (modal.getQuestion().equalsIgnoreCase(keyword)) {
arrayList.add(modal);
}
}
if (arrayList.size() > 0) {
System.out.print("list size "+arrayList.size());
} else {
System.out.print("No records found");
}
return arrayList;
}
}
I leave it to you as an exercise to figure out how this solution works, but feel free to ask any questions you wish.
Java 7 solution:
import java.util.*;
import static org.apache.commons.lang3.StringUtils.trimToEmpty;
public class MaxMatchFinder {
public static void main(String[] args) {
Map<String, Set<String>> tagsByName = new HashMap<>();
tagsByName.put("a", new HashSet<>(Arrays.asList("Hi", "Hello", "Hola", "Bonjour")));
tagsByName.put("b", new HashSet<>(Arrays.asList("Hi", "Hello")));
tagsByName.put("c", new HashSet<>(Arrays.asList("Hi")));
String searchText = "Hi, Hello, Hola";
String[] tagsToFind = searchText.split(",");
Map<String, Integer> matchCountsByEntryName = new HashMap<>();
for (String tagToFind : tagsToFind) {
for (String entryName : tagsByName.keySet()) {
Set<String> tags = tagsByName.get(entryName);
if (tags.contains(trimToEmpty(tagToFind))) {
Integer count = matchCountsByEntryName.get(entryName);
Integer incrementedCount = count == null ? 1 : count + 1;
matchCountsByEntryName.put(entryName, incrementedCount);
}
}
}
List<Map.Entry<String, Integer>> sortedEntries = new ArrayList<>(matchCountsByEntryName.entrySet());
Collections.sort(sortedEntries, new Comparator<Map.Entry<String, Integer>>() {
#Override
public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
return e2.getValue().compareTo(e1.getValue());
}
});
Map.Entry<String, Integer> entryWithMostMatches = sortedEntries.get(0);
System.out.printf("Of the entries to be searched," +
" entry \"%s\" contains the most matches (%d).\n",
entryWithMostMatches.getKey(), entryWithMostMatches.getValue());
}
}
Java 8 solution:
import java.util.*;
import java.util.stream.Collectors;
import static org.apache.commons.lang3.StringUtils.trimToEmpty;
public class MaxMatchFinder {
public static void main(String[] args) {
Map<String, Set<String>> tagsByName = new HashMap<>();
tagsByName.put("a", new HashSet<>(Arrays.asList("Hi", "Hello", "Hola", "Bonjour")));
tagsByName.put("b", new HashSet<>(Arrays.asList("Hi", "Hello")));
tagsByName.put("c", new HashSet<>(Arrays.asList("Hi")));
String searchText = "Hi, Hello, Hola";
String[] tagsToFind = searchText.split(",");
Map<String, Integer> matchCountsByEntryName = new HashMap<>();
Arrays.stream(tagsToFind)
.forEach(tagToFind -> {
for (String entryName : tagsByName.keySet()) {
Set<String> tags = tagsByName.get(entryName);
if (tags.contains(trimToEmpty(tagToFind))) {
matchCountsByEntryName.compute(entryName, (k, v) -> v == null ? 1 : v + 1);
}
}
});
List<Map.Entry<String, Integer>> sortedEntries = matchCountsByEntryName.entrySet().stream()
.sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
.collect(Collectors.toList());
Map.Entry<String, Integer> entryWithMostMatches = sortedEntries.get(0);
System.out.printf("Of the entries to be searched," +
" entry \"%s\" contains the most matches (%d).\n",
entryWithMostMatches.getKey(), entryWithMostMatches.getValue());
}
}
After many days of trying, I think I found solution to my problem. Below is the code I am using now.
public ArrayList<QuestionAnswerModal> filter(String keyword, boolean isQuestionSearch) {
ArrayList<QuestionAnswerModal> arrayList = new ArrayList<>();
HashMap<String, Integer> countList = new HashMap<>();
if (isQuestionSearch) {
for (QuestionAnswerModal modal : questionAnswerArrayList) {
if (modal.getKeyword().equalsIgnoreCase(keyword)) {
arrayList.add(modal);
}
}
return arrayList;
} else {
//will store the index of the question with largest match
int[] count = new int[questionAnswerArrayList.size()];
for (int i = 0; i < questionAnswerArrayList.size(); i++) {
List<String> keywords = new ArrayList<>();
String[] word = questionAnswerArrayList.get(i).getKeyword().split(",");
keywords = Arrays.asList(word);
String[] userKeywords = keyword.split(",");
for (int j = 0; j < userKeywords.length; j++) {
if (keywords.contains(userKeywords[j])) {
if (countList.size() == 0) {
//countList.put(userKeywords[j], 1);
count[i]++;
}
}
}
}
//index with largest match
int largest = 0;
//valu if the index
int largestCount = count[largest];
for (int i = 0; i < count.length; i++) {
if (count[i] > largestCount)
largest = i;
}
arrayList.add(questionAnswerArrayList.get(largest));
if (arrayList.size() > 0) {
lvQuestionAnswer.invalidate();
QuestionAnswerAdapter questionAnswerAdapter = new QuestionAnswerAdapter(arrayList, MainActivity.this, MainActivity.this, MainActivity.this);
lvQuestionAnswer.setAdapter(questionAnswerAdapter);
dialog.dismiss();
} else {
Toast.makeText(MainActivity.this, "No records found", Toast.LENGTH_SHORT).show();
}
return arrayList;
}
}
I am pretty new to TreeMap and TreeSet and the likes and was wondering how to sort the data structures by value? I realise with a TreeSet you can sort it into alphabetical order automatically but I want it to order via value? Any idea on how to do this?
It currently prints like...
aaa: 29
aaahealthart: 30
ab: 23
abbey: 14
abdomin: 3
aberdeen: 29
aberdeenuni: 20
When I want it to print like...
aaahealthart: 30
aaa: 29
aberdeen: 29
ab: 23
aberdeenuni: 20
abbey: 14
abdomin: 3
Here is my method here...
ArrayList<String> fullBagOfWords = new ArrayList<String>();
public Map<String, Integer> frequencyOne;
public void termFrequency() throws FileNotFoundException{
Collections.sort(fullBagOfWords);
Set<String> unique = new TreeSet<String>(fullBagOfWords);
PrintWriter pw = new PrintWriter(new FileOutputStream(frequencyFile));
pw.println("Words in Tweets : Frequency of Words");
for (String key : unique) {
int frequency = Collections.frequency(fullBagOfWords, key);
System.out.println(key + ": " + frequency);
pw.println(key + ": " + frequency);
}
pw.close();
}
Thanks for all the help guys.
TreeMap orders by key, I don't think you can use the same implementation to sort by the value. But you can achieve the task with a slightly different approach:
public Map<String, Integer> countWords(List<String> words) {
Map<String, Integer> result = new Map<>();
for (String word : words) {
if (result.containsKey(word)) {
// the word is already in the map, increment the count
int count = result.get(word) + 1;
result.put(word, count);
} else {
result.put(word, 1);
}
}
return result;
}
Then you just need to sort the elements of the resulting map. You can do this in the following way:
public List<Map.Entry<String, Integer> sortMap(Map<String, Integer> map) {
List<Map.Entry<String, Integer> elements = new LinkedList<>(map.entrySet());
Collections.sort(elements, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 ) {
return o1.getValue().compareTo(o2.getValue());
}
});
}
So you use the first method to count the word frequency and the second to sort by it.
You can create an ArrayList and store each entry in it like this:
ArrayList<Map.Entry<String, Integer> list = new new ArrayList(map.entrySet());
then you can sort the arrayList using a comparator that compares the entries by their value:
Collections.sort(list , new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 ) {
return o1.getValue().compareTo(o2.getValue());
}
});
And then you can print the entries from the arrayList
Try something like this:
Set<Map.Entry<Integer, Integer>> sorted =
new TreeSet<Map.Entry<Integer, Integer>>(new Comparator<Map.Entry<Integer, Integer>> {
public int compare(Map.Entry<Integer, Integer> first, Map.Entry<Integer, Integer> second) {
return first.getValue().compareTo(second.getValue());
}
public boolean equals(Map.Entry<Integer, Integer> that) {
return this.equals(that);
}
});
That should give you what you want.
i'm attempting to reorder an List of Maps in alphabetical order. i can see that the "name" String gets filled out with the appropriate value, but groupDataCopy is never updated. as far as i know, using the new operator and calling "put" will place the value in the Map. but I can see that on the following iteration, the ArrayList contains:
{name = null}
i don't know why i'm losing values in my Map List. here is the code:
private void sortByName() {
List<Map<String, String>> groupDataCopy = new ArrayList<Map<String, String>>();
List<List<Map<String, String>>> childDataCopy = new ArrayList<List<Map<String, String>>>();
int groupPos = 0;
int nextNamePos = 0;
String name = null;
while(groupPos<groupData.size()) {
//main loop
int groupDataComparison = 0;
name = null;
while(groupDataComparison<groupData.size()) {
//comparison traversal for group
if(!groupDataCopy.isEmpty()) { //if groupDataCopy has data
if(groupDataCopy.get(groupDataCopy.size()-1).get("name").compareTo(groupData.get(groupDataComparison).get("name")) > 0) { //if the last index of groupDataCopy is alphabetically after (or equal to) last chosen name
if(name==null || groupData.get(groupDataComparison).get("name").compareTo(name) < 0) {
name = groupData.get(groupDataComparison).get("name");
nextNamePos = groupDataComparison;
}
}
} else {
if(name==null || groupData.get(groupDataComparison).get("name").compareTo(name) < 0) {
name = groupData.get(groupDataComparison).get("name");
nextNamePos = groupDataComparison;
}
}
groupDataComparison++;
}
groupDataCopy.add(new HashMap<String, String>());
groupDataCopy.get(groupPos).put("name", name);
childDataCopy.add(new ArrayList<Map<String, String>>());
for(Map<String, String> data : childData.get(nextNamePos)) {
childDataCopy.get(groupPos).add(data);
}
groupPos++;
}
groupData = groupDataCopy;
childData = childDataCopy;
}
Comparator<Map<String, String> comparator = new Comparator<Map<String, String>()
{
public int compare(Map<String, String> o1, Map<String, String> o2)
{
return o1.get("name").compartTo(o2.get("name");
}
}
Collections.sort(groupData, comparator);
Try creating a Comparator that will let you use Collections.sort:
Something like:
Comparator<Map<String, String> comp = new Comparator<Map<String, String>()
{
public int compare(Map<String, String> o1, Map<String, String> o2)
{
//write code to compare values
}
}
After which you can simply do:
Collections.sort(groupData, comp);
How to get count the same values from HashMAP?
HashMap<HashMap<String, Float>, String> HM=new HashMap<HashMap<String,Float>, String>();
HashMap<String, Float> h;
h=new HashMap<String, Float>();
h.put("X", 48.0f);
h.put("Y", 80.0f);
HM.put(typeValuesHM, "Red");
h=new HashMap<String, Float>();
h.put("X", 192.0f);
h.put("Y", 80.0f);
HM.put(typeValuesHM, "Red");
h=new HashMap<String, Float>();
h.put("X", 192.0f);
h.put("Y", 320.0f);
HM.put(typeValuesHM, "Blue");
h=new HashMap<String, Float>();
h.put("X", 336.0f);
h.put("Y", 560.0f);
HM.put(typeValuesHM, "Blue");
The values of my HashMap HM are as follows:
{ {x=48,y=80}=Red,{x=192,y=80}=Red,{x=192,y=320}=Blue,{x=336,y=560}=Blue }
Here,
I want to count the similar values in the HashMap HM.
ie) if i give value equals to "Red" means i want to get count=2.
if i give value equals to "Blue" means i want to get count=2.
How to get count the same values from HashMAP HM?
int count = Collections.frequency(new ArrayList<String>(HM.values()), "Red");
Loop through the entry set and drop all values to a second map, the first maps value as a key, the value will be the count:
Map<String, Integer> result = new TreeMap<String, Integer>();
for (Map.Entry<Map<String, Float>> entry:HM.entrySet()) {
String value = entry.getValue();
Integer count = result.get(value);
if (count == null)
result.put(value, new Integer(1));
else
result.put(value, new Integer(count+1));
}
The result map for your example should be like this:
{"Red"=2, "Blue"=2} // values are stored as Integer objects
The only way you can do it is to iterate through all the elements and count the occurrences:
for(String value: hm.values()) {
if (value.equals(valueToCompare)) {
count++;
}
}
int countValue(String toMatch) {
int count = 0;
for (String v : HM.values()) {
if (toMatch.equals(value)) {
count++;
}
}
return count;
}
Also, it is probably overkill to use a HashMap as the key if you are just storing two values. The built in Point uses int, but it would not be hard to re-implement with float.
Iterator<String> iter = HM.values().iterator();
while(iter.hasNext()) {
String color = iter.next();
if(color.equals("Red")) {
} else if(color.equals("Green")) {
} else if(color.equals("Blue")) {
}
}