Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching an array list for most common String

Tags:

java

I was wondering how I could search an ArrayList of Strings to find the most commonly occurring 'destination' in an 'Itinerary' object I've created (which contains a list of different destinations.)

So far I have:

public static String commonName(ArrayList<Itinerary> itinerary){

    int count = 0;
    int total = 0;

    ArrayList<String> names = new ArrayList<String>();
    Iterator<String>itr2 = names.iterator();

    while(itr.hasNext()){ 

        Itinerary temp = itr.next();  

        if(temp.iterator().hasNext()){ //if its has destinations

                // Destination object in itinerary object 
                Destination temp2 = temp.iterator().next(); 
                String name = temp2.getDestination().toLowerCase().replace(" ", "");

                if(names.contains(name)){
                    count = count + 1;
                    //do something with counting the occurence of string name here
                }

I'm having problems making an algorithm to search the array for the most commonly occurring string, or strings if there is a tie; and then displaying the number of the 'Itinerary object' (the parameter value) the string is found in. Any help would be great, thank you!!

like image 587
LeighA Avatar asked Feb 27 '23 13:02

LeighA


1 Answers

I would make a HashMap<String,Integer>. Then I would go through each itinerary, and if the destination wans't in the Map I would create an entry with put(destination, 1), otherwise I would increment the count that was there with put(destination, get(destination)+1). Afterwards I'd go through the Map entries and look for the one with the highest count.

like image 52
Paul Tomblin Avatar answered Mar 12 '23 11:03

Paul Tomblin