Compare array to hashset

Hi,Is there a way to compare a hashset and an array, and return on the results that intersect into a new array? I know I could do this using a loop through the array and seeing if the hashset contains the value, but was hoping a better way may exist?Thanks,Craig
[290 byte] By [craig081785a] at [2007-11-27 2:38:55]
# 1

Try this (untested!) code:

public static <T> boolean areEqual(Set<T> set, T[] array) {

return set.equals(new HashSet<T>(Arrays.asList(array)));

}

Edit: Sorry, I only read the compare part, not the intersection part.

prometheuzza at 2007-7-12 3:00:28 > top of Java-index,Java Essentials,New To Java...
# 2

import java.util.*;

public class IntersectionExample {

public static void main(String[] args) {

String[] a = {"a","b","b","c","d","e","f"};

String[] b = {"b","d","f","h","j","k"};

Set < String > sb = new HashSet < String > (Arrays.asList(b));

String[] result = intersection(a, sb);

System.out.println(Arrays.toString(result));

}

public static String[] intersection(String[] a, Set < String > sb) {

Set < String > sa = new HashSet < String > (Arrays.asList(a));

sa.retainAll(sb);

return sa.toArray(new String[0]);

}

}

DrLaszloJamfa at 2007-7-12 3:00:28 > top of Java-index,Java Essentials,New To Java...
# 3
Use the HashSet.contains() method to check if each array element is stored in the set.
hunter9000a at 2007-7-12 3:00:28 > top of Java-index,Java Essentials,New To Java...