有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java快速确定列表是否包含数组中至少一项的方法

我有一个List<String> a和一个String[] b。如果数组中至少有一个列表成员,我想返回true。就这一点而言,我处理的是List<String>String[]并不重要。两者都可能是列表

编辑

Java8似乎为do it via streams提供了一种方法。更基本的方法呢

谢谢


共 (1) 个答案

  1. # 1 楼答案

    没有Java 8流的单向:

    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;
    }
    

    另一种方式:

     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();
     }