Java Collection Element Get getCommonElements( Collection from, Collection to)

Here you can find the source of getCommonElements( Collection from, Collection to)

Description

get Common Elements

License

LGPL

Declaration

public static <E extends Object> List<E> getCommonElements(
            Collection<E> from, Collection<E> to) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.util.ArrayList;
import java.util.Collection;

import java.util.List;

public class Main {
    public static <E extends Object> List<E> getCommonElements(
            List<E> from, List<E> to) {
        List<E> res = new ArrayList<E>();
        for (int i = 0; i < from.size(); i++) {
            if (hasElement(to, from.get(i))) {
                res.add(from.get(i));//from   ww w  . j a v a 2 s. c  om
            }
        }
        return res;
    }

    public static <E extends Object> List<E> getCommonElements(
            List<List<E>> sets) {
        List<E> set = getCommonElements(sets.get(0), sets.get(1));
        for (int i = 2; i < sets.size(); i++) {
            set = getCommonElements(set, sets.get(i));
        }
        return set;
    }

    public static <E extends Object> List<E> getCommonElements(
            Collection<E> from, Collection<E> to) {
        List<E> res = new ArrayList<E>();
        for (E f : from) {
            for (E t : to) {
                if (f.equals(t)) {
                    res.add(f);
                }
            }
        }
        return res;
    }

    public static <E extends Object> boolean hasElement(List<E> array,
            E element) {
        boolean res = false;
        for (int i = 0; i < array.size(); i++) {
            if (array.get(i).equals(element)) {
                res = true;
                break;
            }
        }
        return res;
    }
}

Related

  1. getCommaDelimitedString(Collection elements)
  2. getCommaSeparatedString(Collection collection)
  3. getCommaSeparatedString(Collection values)
  4. getCommaSeparatedStringFromCollection(Collection collections)
  5. getCommon(Collection c1, Collection c2)
  6. getCommonSuffix(Collection c)
  7. getComponentName(Collection existingNames, String name)
  8. getDocIdString(Collection docIds)
  9. getElement(final int index, final Collection coll)