两个字符串数组A和B,寻找相同元素的方法

问题:两个字符串数组A和B,寻找相同元素的方法 ?注意:A、B数组都比较大

第一种::比较A、B找出B与A中不相同的元素,然后再用B减去B与A中不相同的元素即可。

    得到的就是A、B中相同的元素。

第二种:利用Map集合的性质,把数组A的数据作为map的key和value, 然后用B的数据取值,不为NULL,说明相同。

下面直接上代码

    /**
     * 基本思路:相同 = 集合B-(集合B-集合A中相同的=不相同的)
     * 
     * @return
     */
    public List<String> getSameList(String[] strArr1, String[] strArr2) {
        // 数组A
        List<String> coll = Arrays.asList(strArr1);
        // 数组B
        List<String> coll2 = Arrays.asList(strArr2);

        // 数组B的list
        List<String> alter0 = new ArrayList<String>(coll2);

        // 数组A的List
        List<String> alter1 = new ArrayList<String>(coll);

        // 数组B与A不同的元素的List
        List<String> alter2 = new ArrayList<String>(coll2);
        // B中去掉A中相同的元素
        alter2.removeAll(alter1);

        // 数组BList -B中和A不用的List=相同的
        alter0.removeAll(alter2);
        Iterator<String> it2 = alter0.iterator();
        while (it2.hasNext()) {
            System.out.println("数组AB中相同的元素" + it2.next());
        }
        return alter0;
    }

    /**
     * 把数组A的数据作为map的key和value, 然后用B的数据取值,不为NULL,说明相同
     * 
     * Map接口 Map提供了一种映射关系,其中的元素是以键值对(key-value)的形式存储的,能够实现根据key快速查找value;
     * Map中的键值对以Entry类型的对象实例形式存在;
     * 建(key值)不可重复,value值可以重复,一个value值可以和很多key值形成对应关系,每个建最多只能映射到一个值。
     * Map支持泛型,形式如:Map<K,V> Map中使用put(K key,V value)方法添加
     * 
     * HashMap类 HashMap是Map的一个重要实现类,也是最常用的,基于哈希表实现 HashMap中的Entry对象是无序排列的
     * Key值和value值都可以为null,但是一个HashMap只能有一个key值为null的映射(key值不可重复)
     * 
     */
    public List<String> getSameElementByMap(String[] strArr1, String[] strArr2) {

        // HashMap key值 不可重复 Key值和value值都可以为null
        HashMap<String, Object> map = new HashMap<String, Object>();

        // 数组A中的元素放入Map中
        for (String string1 : strArr1) {
            map.put(string1, string1);
        }

        List<String> list = new ArrayList<String>();
        // 用数组B元素做为Key来取值,如为NULL则说明相同
        for (String string2 : strArr2) {
            Object j = map.get(string2);
            if (j != null) {
                list.add(string2);
                // System.out.println("数组AB中相同的元素: "+j.toString());
            }
        }
        return list;

    }

猜你喜欢

转载自www.cnblogs.com/wyf-love-dch/p/9007249.html