Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Count frequency of a string in a given array without using any functions or classes in Java.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Main {
static void staircase(String[] votes) {
ArrayList<String> arrayList = new ArrayList<>();
for(int i = 0; i < votes.length; i++){
arrayList.add(votes[i]);
}
Collections.sort(arrayList);
String[] sortedArray = arrayList.toArray(new String[arrayList.size()]);
int voteCount = 1, winnerCount = 0;
String lastName = "";
String winnerName = sortedArray[sortedArray.length - 1];
for(int i = 0; i < sortedArray.length; i++){
if(sortedArray[i] == lastName) {
voteCount++;
if(voteCount >= winnerCount){
winnerName = lastName;
winnerCount = voteCount;
}
} else {
voteCount = 1;
lastName = sortedArray[i];
}
}
System.out.println(winnerName);
String s = Arrays.toString(arrayList.toArray());
System.out.println(s);
}
public static void main(String[] args) {
String[] array = {"Alex", "Michael", "Harry", "Dave", "Michael", "Victor", "Harry", "Alex", "Mary", "Mary"};
staircase(array);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment