-1

In this program I'm going to have a list of names which will be printed via a system.out.print() method (e.g. system.out.print("Joe, ") after specific actions are taken.

For example, my output would be

Joe, Ben, Ben, Tom, Ben, Joe, Tom, Tom, Joe, Tom

Now I need to find a way using Java to go through the printed list of names and collect the most common one, ideally so it would print something like this after completing the calculation.

The most common name was: Tom

I thought about creating int counters which would increment ++ each time that the name's were printed, but I don't know how to proceed further with this kind of solution. This is probably fairly nooby so I appreciate your time!

j panton
  • 232
  • 4
  • 16

2 Answers2

1

Two ways I can think of:

  1. Create Mapping / Dictionary, use name as a key and count the number of appearance for each name, take the one with maximum counter
  2. Sort the Name List, Loop the sorted list and increase counter for same group of name, reset counter when meet a new name, meanwhile record the name with the maximum count

Both methods give similar complexity

shole
  • 4,046
  • 2
  • 29
  • 69
  • I don't know if it changes things, but the names printed don't come from an array, just a normal if(condition){ print"joe"} kind of way. Can I still sort them? – j panton Feb 26 '16 at 06:35
  • To be said, can you store those in an array? if(condition){ print "joe"; store"joe" in array}? Or your list will change dynamically, and you never know when "condition" would happen? Then you may use Method 1: use mapping / dictionary and insert the name when "condition" happens, query the value with maximum counts afterwards – shole Feb 26 '16 at 07:17
  • 1
    Okay, thankyou, I would tick your answer if I could choose two! :( – j panton Feb 26 '16 at 07:22
1

You can use a HashMap. Declare as follows.

HashMap<String, Integer> hm = new HashMap<>();

To store names as keys and counter for each name use a method like this.

  public HashMap<String, Integer> incrementCountForName(HashMap<String, Integer> hm, String name) {
            if (hm.containsKey(name)) {
                int count = hm.get(name);
                hm.put(name, count + 1);
            } else {
                hm.put(name, 1);
            }
            return hm;
        }

In order to find the max value of the map you can have a look here. There are many goods solutions.

Community
  • 1
  • 1
anaxin
  • 710
  • 2
  • 7
  • 16