獲取List中相同元素和不同元素Demo



import java.util.*;

public class CollectionUtil {
    private CollectionUtil() {
    }

    /**
     * 找出兩個集合中不同的元素
     *
     * @param collmax
     * @param collmin
     * @return
     */
    public static Collection getDifferent(Collection collmax, Collection collmin) {
        //使用LinkedList防止差異過大時,元素拷貝
        Collection csReturn = new LinkedList();
        Collection max = collmax;
        Collection min = collmin;
        //先比較大小,這樣會減少後續map的if判斷次數
        if (collmax.size() < collmin.size()) {
            max = collmin;
            min = collmax;
        }
        //直接指定大小,防止再散列
        Map<Object, Integer> map = new HashMap<Object, Integer>(max.size());
        for (Object object : max) {
            map.put(object, 1);
        }
        for (Object object : min) {
            if (map.get(object) == null) {
                csReturn.add(object);
            } else {
                map.put(object, 2);
            }
        }
        for (Map.Entry<Object, Integer> entry : map.entrySet()) {
            if (entry.getValue() == 1) {
                csReturn.add(entry.getKey());
            }
        }
        return csReturn;
    }

    /**
     * 找出兩個集合中相同的元素
     *
     * @param collmax
     * @param collmin
     * @return
     */
    public static Collection getSame(Collection collmax, Collection collmin) {
        //使用LinkedList防止差異過大時,元素拷貝
        Collection csReturn = new LinkedList();
        Collection max = collmax;
        Collection min = collmin;
        //先比較大小,這樣會減少後續map的if判斷次數
        if (collmax.size() < collmin.size()) {
            max = collmin;
            min = collmax;
        }
        //直接指定大小,防止再散列
        Map<Object, Integer> map = new HashMap<Object, Integer>(max.size());
        for (Object object : max) {
            map.put(object, 1);
        }
        for (Object object : min) {
            if (map.get(object) != null) {
                csReturn.add(object);
            }
        }
        return csReturn;
    }

    /**
     * 獲取兩個集合的不同元素,去除重複
     *
     * @param collmax
     * @param collmin
     * @return
     */
    public static Collection getDiffentNoDuplicate(Collection collmax, Collection collmin) {
        return new HashSet(getDifferent(collmax, collmin));
    }

    public static void main(String[] args) throws Exception {
        List<Integer> num1 = new ArrayList<Integer>();
        List<Integer> num2 = new ArrayList<Integer>();
        num1.add(1);
        num1.add(7);
        num1.add(9);
        num1.add(10);

        num2.add(1);
        num2.add(7);
        num2.add(9);
        num2.add(10);
        num2.add(12);




        Collection different = CollectionUtil.getDifferent(num1, num2);

        System.out.println(different);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章