By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,649 Members | 1,490 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,649 IT Pros & Developers. It's quick & easy.

print out the duplicate of an array only once

P: 1
i want to print out an element of an array only once even if the element has many duplicates. her is the code i have tried;-

Expand|Select|Wrap|Line Numbers
  1.      for(int count=0;count<arr.length;count++){
  2.     int counter = 0;
  3.     char num = arr[count];
  4.       for(int count2=0;count2<arr.length;count2++){
  5.      if(num==arr[count2]){
  6.        counter++; }
  7.     } System.out.println(num + "\t" + counter);}
Dec 28 '12 #1
Share this Question
Share on Google+
2 Replies


Rabbit
Expert Mod 10K+
P: 12,421
Please use code tags when posting code.

That code in no way accounts for duplicates. One method is to remove all occurrences of an element after it has been printed. Another method is to insert what has been printed into another array and check against that array before printing. A third method is to sort the array and then print at each change of value.

Which method you use will depend on your requirements. For example, I would use the second method if I needed to keep the original data intact and in its original order.
Dec 28 '12 #2

100+
P: 185
The fastest and easiest way is to insert all the data into a set. Sets allows no duplicates.
Jan 5 '13 #3

Post your reply

Sign in to post your reply or Sign up for a free account.