So you mean like this?
public static void main(String[] args) {
final Set<String> nounPhrases = new HashSet<>();
nounPhrases.add("java");
nounPhrases.add("jsp");
nounPhrases.add("book");
final Set<String> nounPhrases2 = new HashSet<>();
nounPhrases2.add("web");
nounPhrases2.add("php");
nounPhrases2.add("java");
nounPhrases2.add("book");
// Checking for every element in first set
for (final String element : nounPhrases) {
// if second set has the current element
if (nounPhrases2.contains(element)) {
System.out.println("They have " + element);
}
}
}
My output:
They have java
They have book
Edit:
Based on your comment, if i understand correctly, if you want to get the common elements in both sets, just store the values and return them:
public static void main(String[] args) {
final Set<String> nounPhrases = new HashSet<>();
nounPhrases.add("java");
nounPhrases.add("jsp");
nounPhrases.add("book");
final Set<String> nounPhrases2 = new HashSet<>();
nounPhrases2.add("web");
nounPhrases2.add("php");
nounPhrases2.add("java");
nounPhrases2.add("book");
System.out.println(getCommon(nounPhrases, nounPhrases2));
}
public final static Set<String> getCommon(Set<String> setA, Set<String> setB) {
final Set<String> result = new HashSet<>();
for (final String element : setA) {
if (setB.contains(element)) {
result.add(element);
}
}
return result;
}
You could use generics to make the method work for other elements than strings:
public final static <T> Set<T> getCommon(Set<T> setA, Set<T> setB) {
final Set<T> result = new HashSet<>();
for (final T element : setA) {
if (setB.contains(element)) {
result.add(element);
}
}
return result;
}
If performance is important, you should check sizes first and only iterate over the elements of the smaller set. If you have one set with 1 elements, and one set with 100, starting with the smaller will leve you with one iteration whereas starting with the bigger will leave you with 100 checks where only 1 could have been in both sets.