user3002906
user3002906

Reputation: 33

Trouble putting only unique values into an array

So I have a list of countries that I am reading from a text file and some of the countries are on there more than once. I need to put each country name into a string array without any doubles, or countries put on there twice. I tried using a for loop but could not wrap my head around the logic required for this.

Thanks in advance.

Upvotes: 0

Views: 68

Answers (3)

LadyBytemod7 s
LadyBytemod7 s

Reputation: 51

In order to check to see if a country is in the array, use an if statement. As you read in each country this checks to see if if exists in the array. If it doesn't, it adds the country to the array.

if(!Arrays.asList(yourArr).contains(country)){
     yourArr[i] = country;
    }

Upvotes: 0

Nathan Merrill
Nathan Merrill

Reputation: 8386

There are three different ways I can see this working:

  1. Use a Set. This is the most efficient and easiest, and uses code that works

  2. Each time you read in an element, iterate through the array, and see if the array already contains the element. If it does, don't add it. If you can't use Sets, this is the easiest code to write.

  3. Read in all of the elements, sort the array. Iterate through the array, and if the current element doesn't equal the previous element, then add it to a new array. This is more efficient than #2 (O(nlog(n)) vs O(n^2)), but will require more code.

Upvotes: 0

Aaron C
Aaron C

Reputation: 343

Try using a Set. A Set can contain one and not more than one of a particular instance (instance1.equals(instance2) will not be true).
Instantiate a Set like so:

Set<String> s = new HashSet<String>();

Then use a for loop to add the values.

String[] countries = {"JP", "US", "CN", "RU", "RU"};  //just make pretend these were read from a file.
for (String countryName: countries){
     s.add(countryName); // RU will only be added once
}

System.out.println(s);

Outputs: [JP, US, RU, CN]

Upvotes: 1

Related Questions