查找子集合不是相邻但在java中的顺序相同

时间:2016-11-01 16:09:09

标签: java search collections

我如何在Java(8)中找到一个集合(列表或集合)是否是另一个集合的子集,尽管这些元素并不相邻,例如[1,2,3,4,5]作为大集合,如果我想搜索[2,3,4]返回true,同样[2,5]返回true但是[4,2]返回false虽然4和2在集合中但是顺序不同

是否有实用程序帮助我这样做? 或者一段代码正确地执行此操作?

由于

4 个答案:

答案 0 :(得分:0)

未经过全面测试,但你可以试试这样的事情,

    int[] x = {1,2,3,4,5};
    int[] y = {2,5};
    int yIndex = 0;

    for(int i: x){
        if(y[yIndex] == i){
            yIndex++;
            if(yIndex >= y.length){
                break;
            }
        }
    }

    System.out.println(yIndex == y.length ? "Match" : "Not Match");

答案 1 :(得分:0)

您可以轻松使用Collections提供的一种实用方法,该方法可以完全按照您的意图执行。

    Collections.disjoint(c1, c2)

如果传递的两个集合没有任何共同的项目,反之亦然,则上述方法返回true。正是你想要的东西。

答案 2 :(得分:0)

如果包含b,则此函数返回true。

此函数将集合转换为数组,如果您的集合类未实现.toArray()函数,它将无效!

public class CollectionUtils {
    private CollectionUtils() {
    }

    /**
     * @return true if A contains B in order
     */
    public static <T> boolean checkAcontainsB(Collection<T> a, Collection<T> b) {
        if (a == null || b == null || b.size()>a.size()) {
            return false;
        }
        if (b.isEmpty()) {
            return true;
        }
        final Object[] aElements = a.toArray();
        final Object[] bElements = b.toArray();

        for (int i = 0; i < aElements.length; i++) {

            int bIndex = 0;
            for(int j = i; j< aElements.length; j++) {
                if(aElements[j] == bElements[bIndex]) {
                    bIndex++;
                    if(bIndex>=bElements.length) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

}

你可以测试一下:

@Test
public void test() {
    Assert.assertFalse(CollectionUtils.contains(Arrays.asList(1,2,3,4), Arrays.asList(2,3,4,5)));
    Assert.assertTrue(CollectionUtils.contains(Arrays.asList(1,2,3,4), Arrays.asList(2,3,4)));
    Assert.assertTrue(CollectionUtils.contains(Arrays.asList(1,2,3,4), Arrays.asList(2,4)));
    Assert.assertTrue(CollectionUtils.contains(Arrays.asList(1,2,3,4,1,2,3,4), Arrays.asList(3,4,2)));
    Assert.assertFalse(CollectionUtils.contains(Arrays.asList(1,2,3,4), Arrays.asList(2,3,4,5,6)));
}

答案 3 :(得分:0)

我不知道您的问题的任何通用解决方案,但在下面您可以找到针对您的问题的定制解决方案。

public static boolean containsArray(int[] a, int[] s) {
    if (a == null || s == null) return false;
    if (a.length < s.length) return false;

    int i = -1;
    for (int current : s) {
        do {
            i++;
            if (i == a.length) {
                return false;
            }
        } while (a[i] != current);
    }

    return true;
}