CSC Interview Question: how to find common elements between two collections

Solution: retainAll method do this.
 
public boolean retainAll(Collection<?> c)

Example:
public class Test {   

    public static void main(String [] args){

         LinkedHashSet hs = new LinkedHashSet();
          // add elements to the hash set
          hs.add("B");
          hs.add("A");
          hs.add("D");
          hs.add("E");
          hs.add("C");
          hs.add("F");
          System.out.println(hs);
         
          LinkedHashSet hs2 = new LinkedHashSet();
          hs2.add("E");
          hs2.add("C");
          hs2.add("G");
          System.out.println(hs2);
          boolean retain=hs.retainAll(hs2);
          System.out.println("retain:"+retain);
          System.out.println(hs2);
          System.out.println(hs);       
    }

}
**********************************************
Output:
[B, A, D, E, C, F]
[E, C, G]
retain:true
[E, C, G]
[E, C]

Popular posts from this blog

Can not connect to git using ssh (Permissions 0644 for '/root/.ssh/id_rsa' are too open.

Upload file on Google cloud storage using Java servlet on google app engine

Session timeout interceptor in struts 2