get Different elements between two collection and return a collection - Java java.util

Java examples for java.util:Collection Element

Description

get Different elements between two collection and return a collection

Demo Code


//package com.java2s;
import java.util.Collection;
import java.util.HashMap;

import java.util.LinkedList;
import java.util.Map;

public class Main {
    public static void main(String[] argv) {
        Collection collmax = java.util.Arrays.asList("asdf", "java2s.com");
        Collection collmin = java.util.Arrays.asList("asdf", "java2s.com");
        System.out.println(getDifferent(collmax, collmin));
    }//from   w  ww.  j a  v  a 2  s.  c om

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Collection getDifferent(Collection collmax,
            Collection collmin) {

        Collection csReturn = new LinkedList();
        Collection max = collmax;
        Collection min = collmin;

        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;
    }
}

Related Tutorials