方法:Arrays.binarySearch(Object[] a, Object key)
篩選出兩個數組中相同的值,>= 0 表示相同,< 0 表示不同 。
有相同值是返回元素的下標值。
代碼如下:
String[] aStr = {"一", "二", "三", "四"};
String[] bStr = {"一", "二"};
List<String> same = Lists.newArrayList();
List<String> different = Lists.newArrayList();
for (String str : aStr) {
if (Arrays.binarySearch(bStr, str) >= 0) {
same.add(str);
}
if (Arrays.binarySearch(bStr, str) < 0) {
different.add(str);
}
}
System.out.println("相同的元素:");
same.stream().forEach(item -> {
System.out.println(item);
});
System.out.println("不相同的元素:");
different.stream().forEach(item -> {
System.out.println(item);
});
打印輸出:
相同的元素:
一
二
不相同的元素:
三
四