[英]Differences Between Two Integer Collection
我有兩組整數(即第一組是:2,3,4,5,第二組是1,2,3,6)。 我怎樣才能找到附加數字數組(1,6)和減去數字數組(4,5)? 我說收藏但我把它們留在Set但是如果你有任何其他的想法,我也可以使用它。 我也會在不同的集合中保留附加數字和減去的數字。
我假設你的意思是一組中的元素而不是另一組。
Set<Integer> first = new LinkedHashSet<Integer>(Arrays.asList(2,3,4,5));
Set<Integer> second = new LinkedHashSet<Integer>(Arrays.asList(1,2,3,6));
Set<Integer> addition = subtract(first, second);
Set<Integer> subtracted = subtract( second, first);
public static <T> Set<T> subtract(Set<T> set1, Set<T> set2) {
Set<T> ret = new LinkedHashSet<T>(set1);
ret.removeAll(set2);
return ret;
}
不確定這是否是你需要的,但你可以使用google guava :
import java.util.HashSet;
import java.util.Set;
import com.google.common.collect.Sets;
public class NumbersTest {
public static void main(String[] args) {
Set<Integer> set1 = new HashSet<Integer>(){{add(2);add(3);add(4);add(5);}};
Set<Integer> set2 = new HashSet<Integer>(){{add(1);add(2);add(3);add(6);}};
System.out.println("Nums Unique to set1: " + Sets.difference(set1, set2));
System.out.println("Nums Unique to set2: " + Sets.difference(set2, set1));
}
}
輸出:
Nums Unique to set1: [4, 5]
Nums Unique to set2: [1, 6]
絕對不是最好的解決方案,但是..
public class IntsFind {
public static void main(String[] args) {
List<Integer> first = Arrays.asList(2, 3, 4, 5);
List<Integer> second = Arrays.asList(1, 3, 4, 6);
List<Integer> missing = new LinkedList<Integer>();
List<Integer> added = new LinkedList<Integer>(second);
for (Integer i : first) {
if (!added.remove(i)) {
missing.add(i);
}
}
System.out.println("Missing ints in second: " + missing);
System.out.println("New ints in second: " + added);
}
}
打印:
在第二個中丟失整數:[2,5]第二個新的整數:[1,6]
編輯不需要包裝Arrays.asList,正如@Peter Lawrey指出的那樣
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.