有两个字符串数组a和b,寻找相同元素 (a和b都比较大)

下面是两个实现。

 

package may;



import java.util.ArrayList;

import java.util.Arrays;

import java.util.HashMap;

import java.util.HashSet;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.Set;



public class GetAllSameElement {



    /**

     * 对两个字符串

     * 得到两个字符串中所有相同的元素集

     */

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        String[] str1 = {"A","B","C","D","E","F","G","A"}; 

        String[] str2 = {"C","D","E","F","G","H","I","H","I"};

        

        Set sameSet = getAllSameElement1(str1,str2);

        Iterator itrs=sameSet.iterator();

        while(itrs.hasNext()){

            System.out.println(itrs.next().toString());

        }

        System.out.println("--------------------分割符-------------------------");

        List samelist = getAllSameElement2(str1,str2);

        Iterator itrl=samelist.iterator();

        while(itrl.hasNext()){

            System.out.println(itrl.next().toString());

        }

        

    }

    

    /**

     * 用集合的retainAll方法,

     * set的retainAll性能高于list的retainAll方法。

     */

    public static Set getAllSameElement1(String[] strArr1,

            String[] strArr2) {

        if (strArr1 == null || strArr2 == null) {

            return null;

        }

        List list1 = new ArrayList(Arrays.asList(strArr1));

        Set set1 = new HashSet(list1);

        set1.retainAll(Arrays.asList(strArr2));

        return set1;

    }

    

    /**

     * 构造一个map,将str1中字符串作为key,值任意。

     * 然后再循环str2

     */

    public static List getAllSameElement2(String[] strArr1,

            String[] strArr2) {

        Map map = new HashMap();

        List list = new ArrayList();

        

        for(int i=0;i<strArr1.length;i++){

            if(map.get(strArr1[i])==null){

                map.put(strArr1[i], "1");

            }

        }

        for (int k = 0; k < strArr2.length; k++) {

            if(map.get(strArr2[k])!=null){

                list.add(strArr2[k]);

            }

        }

        return list;

    }

}

你可能感兴趣的:(字符串)