Trying to remember why I did this...
static boolean matchFriend(List<String> friendList, String candidate) {
for (String s : friendList) {
if (s.equals(candidate)) {
return true;
}
}
return false;
}
static boolean evaluateAsFriends(Map<String, List<String>> friendMap, String a, String b) {
for (Map.Entry<String, List<String>> entry : friendMap.entrySet()) {
if (entry.getKey().equals(a)) {
return matchFriend(entry.getValue(), b);
}
}
return false;
}
static void printOutput(Map<String, List<String>> friendMap, String friend, String candidate) {
long end;
long start = System.currentTimeMillis();
System.out.print(String.format("Evaluating %s and %s: ", friend, candidate));
boolean match = evaluateAsFriends(friendMap, friend, candidate);
System.out.print(match);
end = System.currentTimeMillis();
System.out.println(String.format(" ---> Results in %d ms", (end - start)));
}
public static void main(String[] args) {
Map<String, List<String>> friendMap = new HashMap<String, List<String>>();
friendMap.put("Bob", Arrays.asList("Ann", "Sally", "Sue"));
friendMap.put("Ann", Arrays.asList("Bob", "Fred"));
friendMap.put("Fred", Arrays.asList("Tom", "Cathy", "John", "Ann"));
printOutput(friendMap, "Bob", "Sally");
printOutput(friendMap, "Bob", "Fred");
printOutput(friendMap, "Ann", "Tom");
}
Output:
Evaluating Bob and Sally: true ---> Results in 4 ms
Evaluating Bob and Fred: false ---> Results in 0 ms
Evaluating Ann and Tom: false ---> Results in 0 ms
How to efficiently iterate over each Entry in a Map? (Top voted answer for above: answered by @ScArcher2).
Example of using iterator and generics:
Iterator<Map.Entry<String, String>> entries = myMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, String> entry = entries.next();
String key = entry.getKey();
String value = entry.getValue();
// ...
}
Or as suggested by Steve Kuo and @ComFreek
for (Iterator<Map.Entry<K, V>> entries = myMap.entrySet().iterator(); entries.hasNext(); ) {
Map.Entry<K, V> entry = entries.next();
}
@StudioWorks for (Iterator> entries = myMap.entrySet().iterator(); entries.hasNext(); ) { Map.Entry entry = entries.next(); }. By using that construct we limit the scope of (visibility of the variable) entries to the for loop. – ComFreek Mar 13 '15 at 16:33
HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
/*
* Logic to put the Key,Value pair in your HashMap hm
*/
// Print the key value pair in one line.
hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));