Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i'm having 2 string array,

  str1[] = {"a","b","aa","c"} 

and

  str2[] = {"aa","a","b","c","d"}

how can i compare and remove value if exist in both string[], expected result, str3[]= {"d"}

thanks in advance

share|improve this question
    
hi expert, finally i found result for my question, which is List str3= ListUtils.subtract(Arrays.asList(str1), Arrays.asList(str2)); –  Apache Nov 28 '10 at 7:23
    
Didn't know you are using Apache Commons Library ( ref: ListUtils). –  crnlx Nov 28 '10 at 7:41

2 Answers 2

up vote 2 down vote accepted

ts1 will have "d" inside it after these operations.

String str1[] = {"a","b","aa","c"};
String str2[] = {"aa","a","b","c","d"};
TreeSet ts1 = new TreeSet(Arrays.asList(str2));
ts1.removeAll(Arrays.asList(str1));

share|improve this answer

Convert the arrays to a list and add them to a set which will automatically remove duplicates. Use the toArray() method of Set interface to get the elements as an Array.

    String[] str1 = {"a","b","aa","c"};
    String[] str2 = {"aa","a","b","c","d"};

    Set set = new HashSet();
    set.addAll(Arrays.asList(str1));//add first array to set, removes duplicates
    set.addAll(Arrays.asList(str2));//add second array to set, removes duplicates
    String[] str3 = (String[])set.toArray(new String[set.size()]);//convert back to array
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.