How to calculate the intersection of two sets? [duplicate]

Use the retainAll() method of Set: Set<String> s1; Set<String> s2; s1.retainAll(s2); // s1 now contains only elements in both sets If you want to preserve the sets, create a new set to hold the intersection: Set<String> intersection = new HashSet<String>(s1); // use the copy constructor intersection.retainAll(s2); The javadoc of retainAll() says it’s exactly what you … Read more

Hashset vs Treeset

HashSet is much faster than TreeSet (constant-time versus log-time for most operations like add, remove and contains) but offers no ordering guarantees like TreeSet. HashSet the class offers constant time performance for the basic operations (add, remove, contains and size). it does not guarantee that the order of elements will remain constant over time iteration … Read more