用 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
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP