1

I need to create a java program that takes a string array of countries and prints out the name of countries and how many times they are in the in the array.

Example:

 String[] countries = {"Mexico","Russia","USA","Russia","Mexico",
                       "USA","Germany", "Mexico", "Canada" };

I need the output to be:

Mexico 3
Russia 2
USA 2
Germany 1
Canada 1

Here is what i have so far:

public class TestingTwo {

 public static void main (String args[]) {

    String[] countries = {"Mexico","Russia","USA", "Russia","Mexico", "USA","Germany", "Mexico", "Canada" };
    int i;
    int j;


    for(i=0;i<countries.length-1;i++) {
        int count=0;

        for(j=i+1;j<countries.length;j++) {
            if ((countries[i]==countries[j]) && (i != j)) {
                count++;
                System.out.println(countries[j]+ " " + count);
            }
        }
    }
  }//end of main method
}//end of class

The output im getting is:

Mexico 1
Mexico 2
Russia 1
USA 1
Mexico 1

Issue Faced : I am having trouble finding a way to print out the country name only once. I am able get it to where it prints the countries that have duplicates, but it prints it several times. I am also having trouble with int count and how to get calibrate correctly to the amount of duplicates.

Rahul
  • 12,886
  • 13
  • 57
  • 62

3 Answers3

3

Try this

    String[] countries = {"Mexico","Russia","USA","Russia","Mexico",
            "USA","Germany", "Mexico", "Canada" };
    Map<String, Integer> map = new LinkedHashMap<>();
    for (String country : countries) {
        map.compute(country, (k, v) -> v == null ? 1 : v + 1);
    }
    for (Map.Entry<String, Integer> e : map.entrySet()) {
        System.out.println(e.getKey() + " " + e.getValue());
    }
0

If it is possible for you to use Java 8 then I think the accepted answer to this other question would benefit you:

Group by counting in Java8 stream API

Applying it to your problem we could solve it like this:

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.Arrays;

public class TestingTwo{
    public static void main (String[] args){
        String[] countries = {"Mexico","Russia","USA","Russia","Mexico",
                       "USA","Germany", "Mexico", "Canada" };

        Map<String, Long> counted = Arrays.stream(countries)
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        for(String country: counted.keySet()){
            System.out.println(country+" "+counted.get(country));
        }
    }
}
Community
  • 1
  • 1
André Ramos
  • 44
  • 1
  • 4
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient [reputation](http://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](http://stackoverflow.com/help/privileges/comment). - [From Review](/review/low-quality-posts/10985182) – user1140237 Jan 22 '16 at 05:38
  • @user1140237 Would this be an appropriate answer? I'm still getting the hang of it. – André Ramos Jan 22 '16 at 06:23
  • @AndréRamos This is not an inappropriate answer, but it would be a much better answer if you explained *why* this is the answer and how some of the more advanced bits work. In particular the asker seems like a fairly new (Java) programmer, so probably everything from `Map...to..keySet()` is probably incredibly new and confusing. Also adding a pre-Java8 for comparison and those that don't have 8 yet wouldn't go amiss. – John Hascall Jan 22 '16 at 07:58
0

If you are not using Java 8 then you can try following code:

Set<String> uniqueCountries = new HashSet<String>(Arrays.asList(countries));

Iterator iterator = newset.iterator();
while (iterator.hasNext()){
  int count = 0;
  String c = iterator.next(); 
  for(int i=0;i<countries.length;i++) {
    if(c.equals(countries[i])) {
      count++;
    }
  }
  System.out.println(countries[i]+ " " + count);
}

Still this code is not optimized because for every unique country we are traversing the input array.

mrsus
  • 5,446
  • 4
  • 31
  • 44