2016-11-01 21 views
1

如何在Java(8)中查找集合(列表或集合)是否爲另一個集合的子集,儘管元素沒有相鄰的例如[1,2, 3,4,5]作爲大集合,如果我想搜索[2,3,4]返回true,也[2,5]返回true但是[4,2]返回false雖然4和2在收集但不是相同的順序在java中查找子集合不相鄰但按相同順序

是否有一個實用程序幫助我做到這一點? 或一段代碼正確執行此操作?

感謝

+0

您怎麼看待'[1,2,3,4,1,2,3,4]'。它包含了「[3,4,2]」,這是真的嗎? –

回答

0

如果a包含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))); 
} 
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"); 
0

您可以方便地使用由不正是你想要做集合提供了一個實用的方法。

Collections.disjoint(c1, c2) 

上述方法返回true,如果傳遞的兩個集合沒有任何共同的項目和其他方式。正是你想要的東西。

+0

這不是你需要做的事嗎? –

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; 
} 
相關問題