用 Java 在序列中找出重复第二多的单词
要找出 Java 中序列中重复第二多的单词,代码如下所示 −
示例
import java.util.*; public class Demo{ static String second_repeated(Vector<String> my_seq){ HashMap <String, Integer> my_map = new HashMap<String,Integer>(my_seq.size()){ @Override public Integer get(Object key){ return containsKey(key) ? super.get(key) : 0; } }; for (int i = 0; i < my_seq.size(); i++) my_map.put(my_seq.get(i), my_map.get(my_seq.get(i))+1); int first_val = Integer.MIN_VALUE; int sec_val = Integer.MIN_VALUE; Iterator<Map.Entry<String, Integer>> my_iter = my_map.entrySet().iterator(); while (my_iter.hasNext()){ Map.Entry<String, Integer> ent = my_iter.next(); int v = ent.getValue(); if( v > first_val){ sec_val = first_val; first_val = v; } else if (v > sec_val && v != first_val) sec_val = v; } my_iter = my_map.entrySet().iterator(); while (my_iter.hasNext()){ Map.Entry<String, Integer> ent = my_iter.next(); int v = ent.getValue(); if (v == sec_val) return ent.getKey(); } return null; } public static void main(String[] args){ String arr[] = {"This", "sample", "only", "anything", "sample", "from", "sample","only"}; List<String> my_seq = Arrays.asList(arr); System.out.println("The second most repeated word in the sequence is : "); System.out.println(second_repeated(new Vector<>(my_seq))); } }
输出
The second most repeated word in the sequence is : Only
一个名为 Demo 的类包含函数“second_repeated”,该函数创建一个哈希映射并覆盖“get”函数,该函数返回哈希映射中特定值的关键。创建一个迭代器,并使用“hasNext”函数对后续元素进行迭代。
迭代器检查单词重复的次数,并找到重复次数最多的第一个单词并存储。再次执行的动作是
给出重复第二多的单词。主类包含一个字符串数组和一个列表。此字符串数组也转换为列表。“second_repeated”函数在此新列表上调用,并将在控制台上显示相关输出。
Advertisement