1

I want to remove duplicate String values inside my String[], but I am not sure quite how to do that.

Heres an example:

public static void main(String[] args){

  String[] listofWords = new String [5];
  listofWords[0]  = "BMW";
  listofWords[1]  = "Audi";
  listofWords[2]  = "Mercedes";
  listofWords[3]  = "Audi";
  listofWords[4]  = "BMW";
  for(int i = 0; i<listofWords.length-1; i++){
    system.out.println(listofWords[i]);
  }
}

How would I got about deleting the duplicates in this array and only have one of each make?

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
DanZoe
  • 111
  • 1
  • 3
  • 15
  • 1
    use a set if you dont want doubles – Ya Wang Nov 10 '15 at 17:51
  • 3
    Possible duplicate of [How to efficiently remove duplicates from an array without using Set](http://stackoverflow.com/questions/17967114/how-to-efficiently-remove-duplicates-from-an-array-without-using-set) – avalancha Nov 10 '15 at 18:01

7 Answers7

7

You can convert your String[] to Set:

String [] listofWords = new String [5];
listofWords [0]  = "BMW";
listofWords [1]  = "Audi";
listofWords [2]  = "Mercedes";
listofWords [3]  = "Audi";
listofWords [4]  = "BMW";

Set<String> set = new HashSet<String>(Arrays.asList(listofWords));
System.out.println(set); //prints [Audi, Mercedes, BMW]

You can convert the Set back to String[] like this:

listofWords = set.toArray(new String[set.size()]);
thegauravmahawar
  • 2,802
  • 3
  • 14
  • 23
2
  1. If memory is not a concern, convert to a set and back to array, like:

    Set<String> mySet = new HashSet<String>(Arrays.asList(listofWords));
    listofWords = mySet.toArray(new String[mySet.size()]);
    
  2. If you have memory limits then you should sort the array:

    Arrays.sort(listofWords);
    

    Then remove the duplicates, like this:

    public static int removeDuplicates(String[] A) {
      int length=A.length;
      if(length==0 || length==1) return length;
      int i=1;
      for(int j=1; j<length; j++){
        if(!A[j].equals(A[j-1])){
           A[i]=A[j];
          i++;
        }
      }
      if(i<length) A[i]=null;
        return i;
    }
    

    This method will remove the duplicates and return the new array size.

    Eg.

    public static void main(String[] args) {
      String[] listofWords = new String [5];
      listofWords[0]  = "BMW";
      listofWords[1]  = "Audi";
      listofWords[2]  = "Mercedes";
      listofWords[3]  = "Audi";
      listofWords[4]  = "BMW";
      Arrays.sort(listofWords);
      int n=removeDuplicates(listofWords);
      for(int i = 0; i<n; i++){
        System.out.println(listofWords[i]);
      }
    }
    
dan
  • 13,132
  • 3
  • 38
  • 49
  • Thank you, that seemed to do the trick. But memory is also kind of a concern.. How can I achieve this with less memory usage? – DanZoe Nov 10 '15 at 17:58
  • @DanZoe you should amend the question if you want some sort of in-place solution. – jiggy Nov 10 '15 at 18:07
  • @DanZoe I updated my answer with the solution for the memory constraint. – dan Nov 10 '15 at 18:35
2

I would recommend this solution using Java 8 streams

String[] result = Arrays.stream(listofWords).distinct().toArray(s -> new String[s]);

This also addresses the memory concerns you have expressed in the comments. It will just create an array with enough size to store distinct values and store the result there.

As a side note you could have initialized listofWords more easily like this

String[] listofWords = {"BMW", "Audi", "Mercedes", "Audi", "BMW"};
Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
1

//JAVA-8 - Remove Duplicates

    List li1 = new ArrayList<>(Arrays.asList(10, 22, 10, 20, 11, 22));
    
    System.out.println("Duplicate elements: " + li1);
    
    // Create new list from elements of original list
    List li2 = (List) li1.stream().distinct().collect(Collectors.toList());
    
    // ArrayList with duplicates removed
    System.out.println("Non-duplicate elements: " + li2);
0

It is straightforward to do in-place if you don't need to preserve the order of appearance in the array: sort the array first and use two pointers to iterate through the array:

Arrays.sort(listofWords);
int i = 0, j = 0;
while (j < listofWords.length) {
  // Copy the element from the j-th position to the i-th position.
  listofWords[i] = listofWords[j];
  // Increment j while the word at position j equals the word at position i.
  while (j < listofWords.length && listofWords[j].equals(listofWords[i])) {
    ++j;
  }
  // Increment i, to be the next unique element index.
  ++i;
}

// i currently points to the element after the last non-duplicate element, so
// ideally we would throw away elements [i..listofWords.length)
// However, you can't resize an array in Java.
// This loop just nulls out the remaining elements, since their contents are all
// already in the array.
while (i < listofWords.length) {
  listofWords[i++] = null;
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

You can try the below solution :

public static void main(String[] args) {

    String strArray[] =  new String[]{"bmw","audi","bmw","honda","Yamaha","Yamaha","maruti","hyundai","hyundai"};

    HashSet setOfStrings= new HashSet<String>();
    for(int i=0;i<strArray.length;i++){
        boolean result=setOfStrings.add(strArray[i]);
        if(!result){
            System.out.println("duplicate elements include...."+strArray[i]); 
           }
    }
    Object[] newString= new Object[strArray.length];
    newString=setOfStrings.toArray();
    System.out.println("Array without Duplicates......."+Arrays.toString(newString));
}
0
import java.util.Arrays;

/**
 * @author Kishore Diyyana
 * Simple Bruteforce approach
 */
public class RemoveDupilcates {

    public static void main(String[] args) {

        RemoveDupilcates removeDups = new RemoveDupilcates();

        removeDups.removeDups();

    }

    public void removeDups() {
        int[] numbers = new int[] {10, 22, 10, 20, 11, 22};
        int[] temp = new int [numbers.length];
        int count = -1;
        for (int i=0; i<numbers.length;i++) {
            boolean hasFound = false;
            for (int j = i+1; j< numbers.length; j++) {
                if (numbers[i] == numbers[j]) {
                    hasFound = true;
                    break;
                }
            }
            if (!hasFound) {
                count++;
                System.out.println(numbers[i]);
                temp[count] = numbers[i];
            }
        }
        int[] outpout = null;
        if (count < numbers.length) {
            outpout = new int [count];
            System.arraycopy(temp, 0, outpout, 0, count);
        }
        System.out.println(Arrays.toString(outpout));
    }
}
  • //JAVA-8 List li1 = new ArrayList<>(Arrays.asList(10, 22, 10, 20, 11, 22)); System.out.println("Duplicate elements: " + li1); // Create new list from elements of original list List li2 = (List) li1.stream().distinct().collect(Collectors.toList()); // ArrayList with duplicates removed System.out.println("Non-duplicate elements: " + li2); – Kishore Babu Diyyana Jan 12 '21 at 21:19
  • Welcome to SO! First of all you can edit your original answer if you want to add more code. Also, though it is clear you are trying to help OP by giving a code solution, however to make the answer more effective, helpful and clear please explain around the approach you have taken and why? And adding some test results will be a bonus. More : [How to give a good answer?](https://stackoverflow.com/help/how-to-answer) – Vivek Jan 12 '21 at 23:29