java 编写方法获取两个字符串数组中都存在的元素的数量
时间: 2023-02-22 10:09:25 浏览: 59
下面是 Java 代码,实现统计两个字符串数组中都存在的元素数量:
```
import java.util.HashSet;
public class Main {
public static int getIntersectionCount(String[] arr1, String[] arr2) {
HashSet<String> set1 = new HashSet<>();
for (String s : arr1) {
set1.add(s);
}
int count = 0;
for (String s : arr2) {
if (set1.contains(s)) {
count++;
}
}
return count;
}
public static void main(String[] args) {
String[] arr1 = {"a", "b", "c", "d"};
String[] arr2 = {"c", "d", "e", "f"};
System.out.println(getIntersectionCount(arr1, arr2));
}
}
```
运行结果:2,表示两个数组中都存在的元素数量为 2。
相关问题
输入两个数组(数组元素个数6和8),输出在两个数组中都出现的元素用c语言编写
以下是一种可能的实现方式:
```
#include <stdio.h>
int main() {
int array1[6] = {1, 2, 3, 4, 5, 6};
int array2[8] = {2, 4, 6, 8, 10, 12, 14, 16};
int i, j;
printf("Common elements: ");
for (i = 0; i < 6; i++) {
for (j = 0; j < 8; j++) {
if (array1[i] == array2[j]) {
printf("%d ", array1[i]);
break;
}
}
}
printf("\n");
return 0;
}
```
这段代码定义了两个数组 `array1` 和 `array2`,然后使用两个嵌套的循环遍历这两个数组,找出在两个数组中都出现的元素并打印出来。具体来说,对于数组 `array1` 中的每一个元素,都在数组 `array2` 中查找是否存在相同的元素,如果存在则打印出来。为了避免重复输出相同的元素,内部循环使用 `break` 语句跳出循环。最终输出的就是两个数组中都出现的元素。
有两个String[]数组, 如何快速找到在这两个数组中都存在的元素
可以使用HashSet,将一个数组中的所有元素存储到HashSet中,然后遍历另一个数组,在HashSet中查找是否存在相同的元素即可。
示例代码:
```
String[] arr1 = {"a", "b", "c", "d"};
String[] arr2 = {"b", "d", "e", "f"};
Set<String> set = new HashSet<>(Arrays.asList(arr1));
for (String str : arr2) {
if (set.contains(str)) {
System.out.println(str);
}
}
```
输出结果为:
```
b
d
```
这里使用了Arrays.asList()将数组转换为List,然后再将List转换为HashSet。如果数据量较大,使用HashSet可以大大提高查找效率。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)