public static void main(String[] args) throws Exception{
Scanner scan = new Scanner(System.in);
String str_0 = scan.nextLine().trim();
int n = Integer.parseInt(str_0);
ArrayList<String> vector = new ArrayList<>();
for (int i = 0; i < n; i++){
String str_1 = scan.nextLine().trim();
vector.add(str_1);
}
scan.close();
String result = solution(n, vector);
System.out.println(result);
}
public static String solution(int n, ArrayList<String> vector){
String result = "";
HashMap<String, Integer> map = new HashMap<>();
// 循环计数每个字符串出现的次数
for(String c:vector){
if(map.containsKey(c)){
map.put(c,map.get(c)+1);
}else {
map.put(c,1);
}
}
List<Map.Entry<String,Integer>> list = new ArrayList(map.entrySet());
// 根据字符串出现的次数排序
// Collections.sort(list,(o1, o2) ->(o1.getValue()-o2.getValue()));
Collections.sort(list, Comparator.comparingInt(Map.Entry::getValue));
int size = list.size();
if(list.get(size-1).getValue() == list.get(size-2).getValue()){
result = "dogfall";
}else {
result = list.get(size-1).getKey();
}
return result;
}
// 总是提示把下面的代码替换成为另一种写法
Collections.sort(list,(o1, o2) ->(o1.getValue()-o2.getValue()));
Collections.sort(list, Comparator.comparingInt(Map.Entry::getValue));
提示信息:返回与此条目对应的值。如果映射已从支持映射中移除(通过迭代器的移除操作),则此调用的结果是未定义的。(第一种写法的问题 应该就是说如果排序后有remove操作,会报索引越界异常)
运行结果截图
平局:
示例: