[英]How do I save common words from two arrays into a third array?
I am trying to save all common words from arr1 and arr2 and then store to arr3.我正在尝试保存 arr1 和 arr2 中的所有常用词,然后存储到 arr3。
String[] arr1 = {"pEace", "happiness", "Gives", "So", "aaa"};
String[] arr2 = {"pEace", "HappiNess", "joy", "give", "AAA", "enjoy", "learN"};
int k = 0;
String[] arr3 = new String[0];
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i].equalsIgnoreCase(arr2[j])) {
System.out.println(arr1[i]);
arr3[k] = arr1[i];
k++;
}
}
}
System.out.println(Arrays.toString(arr3));
You can convert these arrays to collections and then use the retainAll
method.您可以将这些arrays转换为collections然后使用
retainAll
方法。 It works differently in different collections.它在不同的 collections 中工作方式不同。
// Convert arrays to collections
String[] arr1 = {"pEace", "happiness", "Gives", "So", "aaa", "learn"};
String[] arr2 = {"pEace", "HappiNess", "joy", "give", "AAA", "learN"};
Collection<String> coll1 = Arrays.asList(arr1);
Collection<String> coll2 = Arrays.asList(arr2);
// ArrayList
ArrayList<String> list1 = new ArrayList<>();
ArrayList<String> list2 = new ArrayList<>();
list1.addAll(coll1);
list2.addAll(coll2);
list2.retainAll(list1);
System.out.println(list2); // [pEace]
// TreeSet
TreeSet<String> set1 = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
TreeSet<String> set2 = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
set1.addAll(coll1);
set2.addAll(coll2);
set2.retainAll(set1);
System.out.println(set2); // [AAA, HappiNess, learN, pEace]
See also: Is it possible that TreeSet equals HashSet but not HashSet equals TreeSet另请参阅: TreeSet 是否可能等于 HashSet 但不是 HashSet 等于 TreeSet
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.