1

I have a List<String> a and a String[] b. I would like to return true if there is at least one member of the list inside the array. For that matter, it doesn't matter that I am dealing with a List<String> and an String[]. Both could be lists.

EDIT

Java 8 gives you a way to do it via streams, it seems. What about more basic ways?

Thanks

David Brossard
  • 13,584
  • 6
  • 55
  • 88

1 Answers1

4

One way without Java 8 streams:

public boolean containsAtLeastOne( List<String> a, String[] b ) {
    Set<String> aSet = new HashSet( a );
    for ( s : b ) {
       if ( aSet.contains( s ) ) {
           return true;
       }
    }
    return false;
}

Another way:

 public boolean containsAtLeastOne( List<String> a, String[] b ) {
    Set<String> aSet = new HashSet( a );
    List<String> bList = Arrays.asList(b);

    bList.retainAll( aSet );

    return 0 < bList.size();
 }
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151