package com.codegym.task.task08.task0815;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
/*
Census
*/
public class Solution {
public static HashMap<String, String> createMap() {
HashMap<String, String> map = new HashMap<>();
map.put("Moldova", "Ian");
map.put("Romania", "Vladimir");
map.put("Greece", "Liuda");
map.put("Spain", "George");
map.put("Portugal", "Mauricio");
map.put("Italy", "Vladimir");
map.put("France", "Vladimir");
map.put("Russia", "Ivan");
map.put("Sweden", "John");
map.put("Ukraine", "Vladimir");
return map;
}
public static int getSameFirstNameCount(HashMap<String, String> map, String name) {
ArrayList<String> list = new ArrayList<>(map.values());
ArrayList<Integer> list2 = new ArrayList<>();
for (String s : list) {
list2.add(Collections.frequency(list, s));
}
// System.out.println(list);
// System.out.println(list2);
// System.out.println(Collections.max(list2));
return Collections.max(list2);
}
public static int getSameLastNameCount(HashMap<String, String> map, String lastName) {
ArrayList<String> list = new ArrayList<>(map.keySet());
ArrayList<Integer> list2 = new ArrayList<>();
for (String s : list) {
list2.add(Collections.frequency(list, s));
}
// System.out.println(list);
// System.out.println(list2);
// System.out.println(Collections.max(list2));
return Collections.max(list2);
}
public static void main(String[] args) {
// getSameFirstNameCount(createMap(), "");
// getSameLastNameCount(createMap(), "");
}
}
Why is two last conditions do not verify? In IntelliJ seems to work fine.
Resolved
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
17 October 2019, 14:07solution
Both the getlastname and getfirstname methods are wrong the same way: they both get the count of every name then return the max occurrence. Because last name is the key in this hashmap, 1 is what is always returned, however for first names the number 4 is what is always returned no matter what first name is passed in because "Vladimir" occurs 4 times and it returns the max count. You need to fix this.
You are on the correct path though, Collections.frequency() is the prefect method to solve this, just remember you only need to count the frequency of only the passed in name, not every name that is in the map.
+3
vladimir.plamadeala@endava.com
18 October 2019, 07:02
Thanks man! It is really helpful!
+1
Guadalupe Gagnon
18 October 2019, 13:52
No problem, sometimes you just need another set of eyes to find figure out what is going on.
+1