2014-08-29 43 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()方法將不正是你想要的。

相關問題