How to calculate the intersection of two sets? [duplicate]
问题 This question already has answers here : Closed 7 years ago . Possible Duplicate: Efficiently finding the intersection of a variable number of sets of strings Say, have two Hashset, how to calculate the intersection of them? Set<String> s1 = new HashSet<String>(); Set<String> s2 = new HashSet<String>(); S1 INT S2 ? 回答1: 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