取两个string数组的交集,首先将第一个数组的值作为key,value为false存储在map集合中;然后将第二个数组的值循环去判断map中key是否存在,存在就讲key对应的value改成true,否则不做变化;
最后,取出map中value为true的key,就是两个数组的交集。
备注:方法一当数组中有重复数据时,map设置key时会把重复的值丢掉,方法二会将两个数组中所有重复值打印出来;
方法一:
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 }
方法二:
package com.java8; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class StringArrayTest { public static void main(String[] args) { String[] arr1 = {"112","wqw","2121","112"}; String[] arr2 = {"112","aad","ewqw", "112"}; List list1 = Arrays.asList(arr1); //将数组转化为list List list2 = Arrays.asList(arr2); List list = (List) list1.stream().filter(a -> list2.contains(a)).collect(Collectors.toList()); System.out.println(list); //打印出list String[] arr = (String[])list.toArray(new String[list.size()]); //转化为数组 for (String a:arr){ System.out.println(a); //打印出数组中每个元素 } } }