CSC Interview Question: how to find common elements between two collections
Solution: retainAll method do this.
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]
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
Post a Comment