Write a method counts that accepts a List of integers and a Set of integers as parameters, and returns a map from each value in the set to the number of occurrences of that value in the list.
My solution #1:
public static Map<Integer, Integer> counts(List<Integer> list, Set<Integer> set) {
Map<Integer, Integer> map = new TreeMap<Integer, Integer>();
Iterator<Integer> i = list.iterator();
for(Integer element : set) {
int count = 0;
for(Integer sub : list) {
if(sub == element) {
count++;
}
}
map.put(element, count);
}
return map;
}
My solution #2:
public static Map<Integer, Integer> counts(List<Integer> list, Set<Integer> set) {
Map<Integer, Integer> map = new TreeMap<Integer, Integer>();
Iterator<Integer> i = list.iterator();
for(Integer element : set) {
int count = 0;
while(i.hasNext()) {
if(i.next() == element) {
count++;
}
}
map.put(element, count);
}
return map;
}
Input:
list: [4, -2, 3, 9, 4, 17, 5, 29, 14, 87, 4, -2, 100]
set: [-2, 4, 29]
Expected output:
{-2=2, 4=3, 29=1}
Output for #1:
{-2=2, 4=3, 29=1}
Output for #2:
{-2=0, 4=3, 29=0}
The first one works, but the second one does not. Why? They are essentially the same thing, or am I missing anything? Also, would using a for loop work to traverse through the list? If not, why?
You forget to reset the iterator after each loop, try the following: