可能重复:
java中arraylist的交/并集
您好,我有两个字符串数组。我想要打印出两个数组之间的差异。有没有Java方法可以做到这一点?例如:
String[ ] first={"A","B","C"};
String[ ] second={"C","B"};
并且结果必须是"A"。
感谢所有的评论。
可能重复:
java中arraylist的交/并集
您好,我有两个字符串数组。我想要打印出两个数组之间的差异。有没有Java方法可以做到这一点?例如:
String[ ] first={"A","B","C"};
String[ ] second={"C","B"};
并且结果必须是"A"。
感谢所有的评论。
将数组转换为Set<String>
。
new HashSet<String>(Arrays.asList(array));
并且执行
Set<String> commonOnes = biggerSet.retainAll(smallerSet);
biggerSet.removeAll(commonOnes).add(smallerSet.removeAll(commonOnes))
或者使用guavadifference()
public class SetDifference {
public static void main(String... args) {
String[] arrA = {"1", "2", "3", "4", "5", "25", "10"};
String[] arrB = {"1", "2", "10", "4", "30"};
System.out.println(Arrays.toString(differences(arrA, arrB)));
}
public static String[] differences(String[] first, String[] second) {
String[] sortedFirst = Arrays.copyOf(first, first.length); // O(n)
String[] sortedSecond = Arrays.copyOf(second, second.length); // O(m)
Arrays.sort(sortedFirst); // O(n log n)
Arrays.sort(sortedSecond); // O(m log m)
int firstIndex = 0;
int secondIndex = 0;
LinkedList<String> diffs = new LinkedList<String>();
while (firstIndex < sortedFirst.length && secondIndex < sortedSecond.length) { // O(n + m)
int compare = (int) Math.signum(sortedFirst[firstIndex].compareTo(sortedSecond[secondIndex]));
switch(compare) {
case -1:
diffs.add(sortedFirst[firstIndex]);
firstIndex++;
break;
case 1:
diffs.add(sortedSecond[secondIndex]);
secondIndex++;
break;
default:
firstIndex++;
secondIndex++;
}
}
if(firstIndex < sortedFirst.length) {
append(diffs, sortedFirst, firstIndex);
} else if (secondIndex < sortedSecond.length) {
append(diffs, sortedSecond, secondIndex);
}
String[] strDups = new String[diffs.size()];
return diffs.toArray(strDups);
}
private static void append(LinkedList<String> diffs, String[] sortedArray, int index) {
while(index < sortedArray.length) {
diffs.add(sortedArray[index]);
index++;
}
}
}
String[] arrA = {"1", "2", "3", "4", "5", "25", "10"};
String[] arrB = {"1", "2", "10", "4", "30"};
对于这两个数组,它返回25,3,30。它遗漏了5。
- OpenSource