![](/img/trans.png)
[英]How can I add the matching numbers from two arrays to an empty third array using for and if statements?
[英]How do I save common words from two arrays into a third array?
我正在嘗試保存 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));
您可以將這些arrays轉換為collections然后使用retainAll
方法。 它在不同的 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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.