首页 > 代码库 > 取两个String数组的交集

取两个String数组的交集

 1 import org.testng.annotations.Test;
 2 import java.util.HashMap;
 3 import java.util.LinkedList;
 4 import java.util.List;
 5 import java.util.Map;
 6 
 7 
 8 public class test {
 9     @Test//测试程序
10     public void test(){
11         String[] arr1 = {"112","wqw","2121"};
12         String[] arr2 = {"112","aad","ewqw"};
13         String[] result=StringIntersection(arr1,arr2);
14         for (String str:result){
15             System.out.printf(str);
16         }
17     }
18     //取两个string数组的交集
19     public  String[] StringIntersection(String[] arr1,String[] arr2){
20         Map<String,Boolean> map = new HashMap<String,Boolean>();
21         List<String> list = new LinkedList<String>();
22         //取出str1数组的值存放到map集合中,将值作为key,所以的value都设置为false
23         for (String str1:arr1){
24             if (!map.containsKey(str1)){
25                 map.put(str1,Boolean.FALSE);
26             }
27         }
28         //取出str2数组的值循环判断是否有重复的key,如果有就将value设置为true
29         for (String str2:arr2){
30             if (map.containsKey(str2)){
31                 map.put(str2,Boolean.TRUE);
32             }
33         }
34         //取出map中所有value为true的key值,存放到list中
35         for (Map.Entry<String,Boolean> entry:map.entrySet()){
36             if (entry.getValue().equals(Boolean.TRUE)){
37                 list.add(entry.getKey());
38             }
39         }
40         //声明String数组存储交集
41         String[] result={};
42         return list.toArray(result);
43     }
44 }

 

取两个String数组的交集