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]

Comments

Popular posts from this blog

Read Images from a xlsx file using Apache POI

Struts 2 : Warning :No configuration found for the specified action: 'Login.action' in namespace: '/'

How to create mail message in FRC822 format