Remove duplicate elements in an Array

  1. package com.test.blogger;
  2. /**
  3. * @author EducateJava
  4. */
  5. public class RemoveDuplicatesFromArray {
  6. public static void main(final String[] args) {
  7. final RemoveDuplicatesFromArray removeDuplicatesFromArray = new RemoveDuplicatesFromArray();
  8. final String[] finalArray = removeDuplicatesFromArray
  9. .removeDup(new String[] { "1", "one", "1", "three", "two", "2", "three", "1" });
  10. for (final String obj : finalArray) {
  11. System.out.println(obj);
  12. }
  13. }
  14. public String[] removeDup(final String[] stringArray) {
  15. boolean matched = false;
  16. final String[] res = new String[stringArray.length];
  17. for (int i = 0; i < stringArray.length; i++) {
  18. res[i] = "";
  19. }
  20. int counter = 0;
  21. for (final String element : stringArray) {
  22. for (final String re : res) {
  23. if (element == re) {
  24. matched = true;
  25. break;
  26. } else {
  27. matched = false;
  28. }
  29. }
  30. if (!matched) {
  31. res[counter] = element;
  32. counter++;
  33. }
  34. }
  35. return res;
  36. }
  37. }
  38.  
Output:
=======
1
one
three
two
2
img logo

No comments :

Post a Comment