yagoTea
yagoTea

Reputation: 51

I want to remove all duplicates in an array and then write the results to an empty array

I want to remove all duplicates in an array and then write the results to an empty array.

Here is what I have so far...

String arIndex[] = new String[rows];    
String value[]; //This is my empty array


for(int i = 0; i < rows; i++) {
    if (Arrays.asList(value).contains(arIndex)) {
        out.println("Already Exist!");
    } else {
        asList[i] = value[i];
    }
}

Could someone give me an idea on how to accomplish this?


Thanks

Upvotes: 4

Views: 102

Answers (3)

Shar1er80
Shar1er80

Reputation: 9041

Since you're dealing with Strings, as long as your result doesn't have to account for case sensitive, you can use a HashMap to count your occurrences. Then when your HashMap is populated, you can iterate through it and move all occurrences whose value is 1 (Not duplicated) to an array (List of some sort).

You'll see in my code sample that each string becomes a key in my HashMap and the count of the key is the value. I don't care about casing which is why in the results you'll see that Hello and hello are not considered duplicated. If you want to consider that duplicated then you can modified my sample code to ignore case.

public static void main(String[] args) throws Exception {
    String[] arIndex = new String[] {"the", "the", "1", "2", "Hello", "hello", "2"};
    Map<String, Integer> occurrences = new HashMap<>();

    // Count occurences of each string in the array
    for (int i = 0; i < arIndex.length; i++) {
        if (occurrences.containsKey(arIndex[i])) {
            occurrences.put(arIndex[i], occurrences.get(arIndex[i]) + 1);
        } else {
            occurrences.put(arIndex[i], 1);
        }
    }

    List<String> nonDuplicatesList = new ArrayList<>();
    for (Map.Entry<String, Integer> occurrence : occurrences.entrySet()) {
        if (occurrence.getValue() == 1) {
            nonDuplicatesList.add(occurrence.getKey());
        }
    }

    // Only do this if you're bounded to an array, otherwise just use the nonDuplicatesList
    Object[] value = nonDuplicatesList.toArray();
    System.out.println(Arrays.toString(value));
}

Results:

enter image description here

Update

After seeing your comment, that an array with values [1, 1, 2, 3] should result in [1, 2, 3], the following code change get's you that.

public static void main(String[] args) throws Exception {
    String[] arIndex = new String[] {"the", "the", "1", "2", "Hello", "hello", "2"};
    Map<String, Integer> occurrences = new HashMap<>();

    for (int i = 0; i < arIndex.length; i++) {
        if (occurrences.containsKey(arIndex[i])) {
            // Ignore this value cause it's a duplicate
            continue;
        } else {
            occurrences.put(arIndex[i], 1);
        }
    }

    arIndex = new String[occurrences.size()];
    occurrences.keySet().toArray(arIndex);

    System.out.println(Arrays.toString(arIndex));
}

Results:

enter image description here

Update

Another way with just an ArrayList

public static void main(String[] args) throws Exception {
    String[] arIndex = new String[] {"the", "the", "1", "2", "Hello", "hello", "2"};

    List<String> removedDuplicates = new ArrayList<>();
    for (String arIndex1 : arIndex) {
        if(!removedDuplicates.contains(arIndex1)) {
            removedDuplicates.add(arIndex1);
        }
    }

    // Setting the removedDuplicates to arIndex
    arIndex = new String[removedDuplicates.size()];
    removedDuplicates.toArray(arIndex);
    System.out.println(Arrays.toString(arIndex));
}

Results:

enter image description here

Upvotes: 2

Joffrey
Joffrey

Reputation: 37729

Arrays are statically allowed, with a fixed size. Collections are more appropriate in java, and available in the java.util package. You'll find the most common data structures, such as lists, queues, sets, maps etc.

In your specific case, you should use Set, which inherently removes duplicates. So you would just add everything to it with the add() method, and duplicates would be automatically ignored:

String arIndex[] = new String[rows];
// arIndex is probably filled with something useful here

Set<String> output = new HashSet<>(); // this set will hold your non-duplicated elements

for (String s : arIndex) { 
    output.add(s); // add() ignores the element if already present
}

// now output contains all your values only once:
for (String s : output) { 
    System.out.println(s); 
}

Then, if you really need the output as an array (which you actually should not need), you can use the following after the loop:

String[] outputArray = output.toArray(new String[output.size()]);

Upvotes: 2

Alex
Alex

Reputation: 4473

Suggestion for beginners - try not to bring your experience but enjoy Java. Don't use arrays - use Collections. Don't check what is already checked - duplication in particular. Then your code will look like Java code:

TreeSet<String> set=new TreeSet<String>(); // TreeSet has no duplication
set.add(value); //  add something
set.addAll(anotherSet); // better choice

Upvotes: 1

Related Questions