使用List、Set等求交集和并集

来源:互联网 发布:培训机构垃圾 知乎 编辑:程序博客网 时间:2024/05/19 14:55

1.    //求两个字符串数组的并集,利用set的元素唯一性  

2.       public static String[] union(String[] arr1, String[] arr2) {  

3.           Set<String> set = new HashSet<String>();  

4.           for (String str : arr1) {  

5.               set.add(str);  

6.           }  

7.           for (String str : arr2) {  

8.               set.add(str);  

9.           }  

10.          String[] result = {};  

11.          return set.toArray(result);  

12.      }  

13.    

14.      //求两个数组的交集  

15.      public static String[] intersect(String[] arr1, String[] arr2) {  

16.          Map<String, Boolean> map = new HashMap<String, Boolean>();  

17.          LinkedList<String> list = new LinkedList<String>();  

18.          for (String str : arr1) {  

19.              if (!map.containsKey(str)) {  

20.                  map.put(str, Boolean.FALSE);  

21.              }  

22.          }  

23.          for (String str : arr2) {  

24.              if (map.containsKey(str)) {  

25.                  map.put(str, Boolean.TRUE);  

26.              }  

27.          }  

28.    

29.          for (Entry<String, Boolean> e : map.entrySet()) {  

30.              if (e.getValue().equals(Boolean.TRUE)) {  

31.                  list.add(e.getKey());  

32.              }  

33.          }  

34.    

35.          String[] result = {};  

36.          return list.toArray(result);  

37.      }  

0 0