Find the second most repeated word in a sequence in Java


To find the second most repeated word in a sequence in Java, the code is as follows −

Example

 Live Demo

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)));
   }
}

Output

The second most repeated word in the sequence is :
Only

A class named Demo contains the function ‘second_repeated’ that creates a hash map and overrides the ‘get’ function that returns the key of a specific value in the hash map. An iterator is created, and the subsequent elements are iterated over using the ‘hasNext’ function.

The iterator checks to see the number of times words were repeated and the first word that is repeated highest number of times is found and stored. Again the action is performed that would

give the second most repeated word. The main class contains a string array and a list. This string array is converted into a list as well. The function ‘second_repeated’ function is called on this new list and the relevant output is displayed on the console.

Updated on: 08-Jul-2020

488 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements