2014-08-29 37 views
3

存在一个问题,那就是如何找到两个字符串数组之间的非常见元素。例如:找到两个字符串数组之间的非常见元素

String[] a = {"a", "b", "c", "d"}; 
String[] b = {"b", "c"}; 
// O/p should be a,d 

我曾尝试下面的方法,但请告知是否有其他有效的方法来达到同样的

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

Set<String> set = new HashSet<>(a.length); 
for (String s : a) { 
    set.add(s); 
} 
for (String s : b) { 
    set.remove(s); 
} 
return set; 

请指教还有没有其他有效的方法,我们也可以在Java中实现这一点

+0

在上面的例子中'b'是'a'的一个子集。如果情况并非如此,您期望什么产出? – AKS 2014-08-29 14:25:31

+0

http://java67.blogspot.de/2014/05/how-to-compare-two-arrays-in-java-string-int-example.html阅读此内容,你会发现你需要做的。 – Paulquappe 2014-08-29 14:25:38

+2

鉴于您陈述的问题,您的解决方案不正确。如果“e”在字符串[] b中呢? – ControlAltDel 2014-08-29 14:27:46

回答

4

这似乎是使用Java的最有效的方法。不过,你可以把它缩短了使用addAllremoveAllretainAll

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

//this is to avoid calling Arrays.asList multiple times 
List<String> aL = Arrays.asList(a); 
List<String> bL = Arrays.asList(b); 

//finding the common element for both 
Set<String> common = new HashSet<>(aL); 
common.retainAll(bL); 

//now, the real uncommon elements 
Set<String> uncommon = new HashSet<>(aL); 
uncommon.addAll(bL); 
uncommon.removeAll(common); 
return uncommon; 

运行示例:http://ideone.com/Fxgshp

+0

与问题中使用的方法有何不同? – 2014-08-29 14:26:11

+0

@mohaned *这似乎是使用Java的最有效的方法。 **尽管如此,你可以缩短**。* – 2014-08-29 14:26:32

+0

我知道它更短,但效率更高吗? – 2014-08-29 14:27:21

0

使用Apache下议院Lang3库的ArrayUtils,你可以这样做:

String[] nonCommon = ArrayUtils.addAll(
     ArrayUtils.removeElements(a, b), 
     ArrayUtils.removeElements(b, a)); 

我不能说它的性能效率,但它更有效写,因为它是一个单一的代码行,你不需要创建和操作集。

这种方法捕获阵列b不同的元素,以及,如本Groovy的测试用例

@Grab('org.apache.commons:commons-lang3:3.3.2') 
import org.apache.commons.lang3.ArrayUtils 

String[] a = ["a", "b", "c", "d"] 
String[] b = ["b", "c", "e"] 

assert ["a", "d", "e"] == ArrayUtils.addAll(ArrayUtils.removeElements(a, b), ArrayUtils.removeElements(b, a)) 
+0

你可能想更新你的链接http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ArrayUtils.html – JustinKSU 2014-08-29 14:41:25

+0

@JustinKSU谢谢,修复它 – bdkosher 2014-08-29 14:44:38

0

阿帕奇百科全书集合CollectionUtils有一个名为disjunction()方法将不正是你想要的。

相关问题