jazz199
jazz199

Reputation: 961

Intersection of 2 arrays using sets

My requirement is the if i have 2 strings, i should get the intersection of 2 strings-means returning the common elements of the strings without duplicacy.

My approach was:

String str1="Character";
String str2="National";

Set<Character> set1=new HashSet<Character>();
Set<Character> set2=new HashSet<Character>();

for(char c:str1.toLowerCase().toCharArray()){
    set1.add(c);
}

for(char c:str2.toLowerCase().toCharArray()){
    set2.add(c);
}

Set<Character> inter=new HashSet<Character>(set1);
Set<Character> union=new HashSet<Character>(set1);

inter.retainAll(set2);
union.addAll(set2);

Now the intersection contains the intersection and union contains the union as:

Intersection of sets:[t, a] Union of sets:[t, e, c, r, a, n, o, l, h, i]

But i want is to convert these sets back to strings as "ta" and"tecranolhi" .

I am using String arr1[]=inter.toArray(new String[0]); but it gives an error.

**Exception in thread "main" java.lang.ArrayStoreException: java.lang.Character
        at java.util.AbstractCollection.toArray(Unknown Source)
        at StringInter.main(StringInter.java:22)**

Can someone clarify this?

Upvotes: 0

Views: 399

Answers (3)

Alexis C.
Alexis C.

Reputation: 93902

As I said, create a StringBuilder, iterate through the Set and append each character. Finally, call sb.toString() and assign back this result to your String variable.

Here's also a solution :

String s = inter.stream().collect(StringBuilder::new, 
                                  StringBuilder::append,
                                  StringBuilder::append).toString();

Upvotes: 3

Mohamed Idris
Mohamed Idris

Reputation: 442

Please refer to the code snippet below:

StringBuffer b = new StringBuffer();
Iterator i = inter.iterator();
while(i.hasNext())
{
  b.append(i.next().toString());
}
String interString = b.toString();

Now, interString will have what you want. Hope this helps.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692271

StringBuilder builder = new StringBuilder();
for (Character c : inter) {
    builder.append(c.charValue());
}
String interAsString = builder.toString();

Upvotes: 2

Related Questions