Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Strings with same characters in a String Array

I'm facing a problem right now. In one of my program, I need to remove strings with same characters from an Array. For eg. suppose,

I have 3 Arrays like,

String[] name1 = {"amy", "jose", "jeremy", "alice", "patrick"};
String[] name2 = {"alan", "may", "jeremy", "helen", "alexi"};
String[] name3 = {"adel", "aron", "amy", "james", "yam"};

As you can see, there is a String amy in the name1 array. Also, I have strings like may, amy and yam in the next two arrays. What I need is that, I need a final array which does not contain these repeated Strings. I just need only one occurrence: I need to remove all permutations of a name in the final array. That is the final array should be:

String[] finalArray={"amy", "jose", "alice", "patrick","alan", "jeremy", "helen", "alexi","adel", "aron", "james"}

(The above array removed both yam, may, and only includes amy).

What i have tried so far, using HashSet, is as below

String[] name1 = {"Amy", "Jose", "Jeremy", "Alice", "Patrick"};
String[] name2 = {"Alan", "mAy", "Jeremy", "Helen", "Alexi"};
String[] name3 = {"Adel", "Aaron", "Amy", "James", "Alice"};
Set<String> letter = new HashSet<String>();
for (int i = 0; i < name1.length; i++) {
    letter.add(name1[i]);
}
for (int j = 0; j < name2.length; j++) {
    letter.add(name2[j]);
}
for (int k = 0; k < name3.length; k++) {
    letter.add(name3[k]);
}
System.out.println(letter.size() + " letters must be sent to: " + letter);

But, the problem with this code is that, it just removes multiple occurences of the same string. Is there any other alternative? Any help is very much appreciated.

like image 734
Lal Avatar asked Jun 23 '15 06:06

Lal


People also ask

How do you remove a character from an array of strings?

foreach(string element in elements) element = element. Replace("\"", string. Empty);

How do you remove duplicates from a string array in Java?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.

How do you remove common characters from two strings?

first, instead of transferring the strings to two arrays, I simply run through the strings. Then I collected all the common chars from str and str2 to a string - commonChars. Then, on the second for loop, I ran through commonChars, and used the String. replace() function to replace all common chars from both strings.


3 Answers

You can sort the character array of the String (str.toCharArray ()) and create a new String from the sorted array to get a "canonical" representation of a String.

Then you can add these Strings to a Set, and check for each String whether the canonical representation is already in the Set.

Set<String> letter = new HashSet<String>();
for (int i = 0; i < name1.length; i++) {
    char[] chars = name1[i].toCharArray();
    Arrays.sort(chars);
    letter.add(new String(chars));
}
for (int j = 0; j < name2.length; j++) {
    char[] chars = name2[j].toCharArray();
    Arrays.sort(chars);
    letter.add(new String(chars));
}
for (int k = 0; k < name3.length; k++) {
    char[] chars = name3[k].toCharArray();
    Arrays.sort(chars);
    letter.add(new String(chars));
}

EDIT : I changed the Set<char[]> to Set<String>, since arrays don't override hashCode and equals, so HashSet<char[]> wouldn't work.

like image 70
Eran Avatar answered Oct 22 '22 17:10

Eran


TreeSet allows us to give a comparator. See whether this helps. For keeping the count use a TreeMap.

package empty;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

public class RemoveDuplicateStrings {

    public static void main(String[] args) {
        String[] name1 = { "amy", "jose", "jeremy", "alice", "patrick" };
        String[] name2 = { "alan", "may", "jeremy", "helen", "alexi" };
        String[] name3 = { "adel", "aron", "amy", "james", "yam" };

        Comparator<String> comparator = new Comparator<String>() {
            @Override public int compare(String o1, String o2) {
                System.out.println("Compare(" + o1 + "," + o2 + ")");
                char[] a1 = o1.toCharArray();
                Arrays.sort(a1);
                char[] a2 = o2.toCharArray();
                Arrays.sort(a2);
                return new String(a1).compareTo(new String(a2));
            }
        };
        Set<String> set = new TreeSet<String>(comparator);

        for (String name : name1) {
            set.add(name);
        }
        for (String name : name2) {
            set.add(name);
        }
        for (String name : name3) {
            set.add(name);
        }

        String[] result = set.toArray(new String[set.size()]);
        System.out.println(Arrays.asList(result));

        // Using TreeMap to keep the count.

        TreeMap<String, Integer> map = new TreeMap<String, Integer>(comparator);

        addAll(name1, map);
        addAll(name2, map);
        addAll(name3, map);

        System.out.println(map);
    }

    private static void addAll(String[] names, TreeMap<String, Integer> map) {
        for (String name : names) {
            if (map.containsKey(name)) {
                int n = map.get(name);
                map.put(name, n + 1);
            } else
                map.put(name, 1);
        }
    }
}
like image 7
Dakshinamurthy Karra Avatar answered Oct 22 '22 15:10

Dakshinamurthy Karra


In line with kdm:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RemoveDuplicateString {

    private static boolean add(Set<String> keySet, String s){
        char[] sortCharacters = s.toCharArray();
        Arrays.sort(sortCharacters);
        return keySet.add(new String(sortCharacters));
    }

    private static void check(Set<String> keySet, String []names, List<String> result){
        for (String name : names) {
            if (add(keySet, name)){
                result.add(name);
            }
        }
    }

    public static void main(String[] args) {
        String[] name1 = {"amy", "jose", "jeremy", "alice", "patrick"};
        String[] name2 = {"alan", "may", "jeremy", "helen", "alexi"};
        String[] name3 = {"adel", "aron", "amy", "james", "yam"};
        Set<String> keySet = new HashSet<String>();
        List<String> result = new ArrayList<String>();
        check(keySet, name1, result);
        check(keySet, name2, result);
        check(keySet, name3, result);
        System.out.println(result);
    }
}
like image 2
David Pérez Cabrera Avatar answered Oct 22 '22 17:10

David Pérez Cabrera