遍历并比较 2 个数组列表并找到匹配项

loop through and compare 2 array lists and find a match

我有 2 个数组列表。我想 return 两者之间的唯一值。这是怎么做到的?

String[] s1 = {10, 1};
String[] s2 = {10, 1, 13};

//loop through and compare element of s1 to s2     
//switch varialbe used to indicate whether a match was found
boolean matchFound = false;

//outer loop for all the elements in s2
for (int i = 0; i < s2.lenght; i++) {
  //inner loop for all the elements in s1
  for (int i = 0; i < s1.lenght; i++) {
     matchFound = true;
     System.out.println("This " + s2[i] + "was found");
  }
}
if(matchFound == false) {
  System.out.println("This " + s2[i] + "was not found");
}
//set matchFound bool back to false
matchFound = false;
}

我用正确答案更新了我的问题。

如果您的数组没有重复值,或者您只对未出现的元素感兴趣,那么您可以使用 Set。

将数组转换为两组:

Set<T> one = new HashSet<T>(Arrays.asList(s1));

Set<T> two = = new HashSet<T>(Arrays.asList(s2));

one.removeAll(secondSet);

two.removeAll(firstSet);

如果两个集合都是空的,那么两个集合是相等的,否则每个集合都有唯一的元素。