If you want to find the second most repeated word in a sequence using Java programming languages, then this is for you. In this example, I have shared how to find out the second most repeated word in Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | import java.util.*; class RepeatedWordProgram { // Method to find the word static String secMostRepeated(Vector<String> seq) { // Store all the words with its occurrence HashMap<String, Integer> occ = new HashMap<String,Integer>(seq.size()){ @Override public Integer get(Object key) { return containsKey(key) ? super.get(key) : 0; } }; for (int i = 0; i < seq.size(); i++) occ.put(seq.get(i), occ.get(seq.get(i))+1); // find the second largest occurrence int first_max = Integer.MIN_VALUE, sec_max = Integer.MIN_VALUE; Iterator<Map.Entry<String, Integer>> itr = occ.entrySet().iterator(); while (itr.hasNext()) { Map.Entry<String, Integer> entry = itr.next(); int v = entry.getValue(); if( v > first_max) { sec_max = first_max; first_max = v; } else if (v > sec_max && v != first_max) sec_max = v; } // Return string with occurrence equals to sec_max itr = occ.entrySet().iterator(); while (itr.hasNext()) { Map.Entry<String, Integer> entry = itr.next(); int v = entry.getValue(); if (v == sec_max) return entry.getKey(); } return null; } // main method public static void main(String[] args) { String arr[] = { "ccc", "aaa", "ccc", "ddd", "aaa", "aaa" }; List<String> seq = Arrays.asList(arr); System.out.println(secMostRepeated(new Vector<>(seq))); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.