Java Code Examples for org.apache.commons.collections4.CollectionUtils#intersection()

The following examples show how to use org.apache.commons.collections4.CollectionUtils#intersection() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CollectionCompareTests.java    From java_in_examples with Apache License 2.0 6 votes vote down vote up
private static void testIntersect() {
    Collection<String> collection1 = Lists.newArrayList("a1", "a2", "a3", "a1");
    Collection<String> collection2 = Lists.newArrayList("a4", "a8", "a3", "a5");
    Set<String> set1 = Sets.newHashSet("a1", "a2", "a3", "a1");
    Set<String> set2 = Sets.newHashSet("a4", "a8", "a3", "a5");
    MutableSet<String> mutableSet1 = UnifiedSet.newSetWith("a1", "a2", "a3", "a1");
    MutableSet<String> mutableSet2 = UnifiedSet.newSetWith("a4", "a8", "a3", "a5");

    // Get all common elements in two collection
    Set<String> jdk = new HashSet<>(set1); // using JDK
    jdk.retainAll(set2);
    Set<String> guava = Sets.intersection(set1, set2); // using guava
    Collection<String> apache = CollectionUtils.intersection(collection1, collection2);  // using Apache
    Set<String> gs = mutableSet1.intersect(mutableSet2); // using GS
    System.out.println("intersect = " + jdk + ":" + guava + ":" + apache + ":" + gs); // print intersect = [a3]:[a3]:[a3]:[a3]
}
 
Example 2
Source File: CollectionCompareTests.java    From java_in_examples with Apache License 2.0 6 votes vote down vote up
private static void testIntersect() {
    Collection<String> collection1 = Lists.newArrayList("a1", "a2", "a3", "a1");
    Collection<String> collection2 = Lists.newArrayList("a4", "a8", "a3", "a5");
    Set<String> set1 = Sets.newHashSet("a1", "a2", "a3", "a1");
    Set<String> set2 = Sets.newHashSet("a4", "a8", "a3", "a5");
    MutableSet<String> mutableSet1 = UnifiedSet.newSetWith("a1", "a2", "a3", "a1");
    MutableSet<String> mutableSet2 = UnifiedSet.newSetWith("a4", "a8", "a3", "a5");

    // Найти все общие элементы у двух коллекций
    Set<String> jdk = new HashSet<>(set1); // c помощью JDK
    jdk.retainAll(set2);
    Set<String> guava = Sets.intersection(set1, set2); // с помощью guava
    Collection<String> apache = CollectionUtils.intersection(collection1, collection2);  // c помощью Apache
    Set<String> gs = mutableSet1.intersect(mutableSet2); // c помощью GS
    System.out.println("intersect = " + jdk + ":" + guava + ":" + apache + ":" + gs); // напечатает intersect = [a3]:[a3]:[a3]:[a3]
}
 
Example 3
Source File: DependencyFanInNode.java    From gocd with Apache License 2.0 6 votes vote down vote up
private void validateIfRevisionMatchesTheCurrentConfigAndUpdateTheMaterialMap(FanInGraphContext context, Pair<StageIdentifier, List<FaninScmMaterial>> stageIdentifierScmPair) {
    final Set<MaterialConfig> currentScmMaterials = context.pipelineScmDepMap.get(materialConfig);
    final Set<FaninScmMaterial> scmMaterials = new HashSet<>(stageIdentifierScmPair.last());
    final Set<String> currentScmFingerprint = new HashSet<>();
    for (MaterialConfig currentScmMaterial : currentScmMaterials) {
        currentScmFingerprint.add(currentScmMaterial.getFingerprint());
    }
    final Set<String> scmMaterialsFingerprint = new HashSet<>();
    for (FaninScmMaterial scmMaterial : scmMaterials) {
        scmMaterialsFingerprint.add(scmMaterial.fingerprint);
    }
    final Collection commonMaterials = CollectionUtils.intersection(currentScmFingerprint, scmMaterialsFingerprint);
    if (commonMaterials.size() == scmMaterials.size() && commonMaterials.size() == currentScmMaterials.size()) {
        stageIdentifierScmMaterial.put(stageIdentifierScmPair.first(), scmMaterials);
        ++currentCount;
    } else {
        Collection disjunctionWithConfig = CollectionUtils.disjunction(currentScmFingerprint, commonMaterials);
        Collection disjunctionWithInstance = CollectionUtils.disjunction(scmMaterialsFingerprint, commonMaterials);

        LOGGER.warn("[Fan-in] - Incompatible materials for {}. Config: {}. Instance: {}.", stageIdentifierScmPair.first().getStageLocator(), disjunctionWithConfig, disjunctionWithInstance);

        //This is it. We will not go beyond this revision in history
        totalInstanceCount = currentCount;
    }
}
 
Example 4
Source File: ReplicasHelper.java    From pg-index-health with Apache License 2.0 5 votes vote down vote up
@Nonnull
static List<UnusedIndex> getUnusedIndexesAsIntersectionResult(
        @Nonnull final List<List<UnusedIndex>> potentiallyUnusedIndexesFromAllHosts) {
    LOGGER.debug("potentiallyUnusedIndexesFromAllHosts = {}", potentiallyUnusedIndexesFromAllHosts);
    Collection<UnusedIndex> unusedIndexes = null;
    for (List<UnusedIndex> unusedIndexesFromHost : potentiallyUnusedIndexesFromAllHosts) {
        if (unusedIndexes == null) {
            unusedIndexes = unusedIndexesFromHost;
        }
        unusedIndexes = CollectionUtils.intersection(unusedIndexes, unusedIndexesFromHost);
    }
    final List<UnusedIndex> result = unusedIndexes == null ? Collections.emptyList() : new ArrayList<>(unusedIndexes);
    LOGGER.debug("Intersection result {}", result);
    return result;
}
 
Example 5
Source File: DGEMatrix.java    From Drop-seq with MIT License 5 votes vote down vote up
/**
 * Merges two DGE matrixes together.  This retains all columns in both experiments, and adds rows that are missing in either data set.
 * The missing values are set to <missingValue>.
 * If the two experiments have overlapping cell barcodes, throw an IllegalArgumentException.
 * @param other The other data set to merge with this one.
 * @return a new DGEMatrix containing the merge of the this with other.
 */
public DGEMatrix mergeDisjointCells (final DGEMatrix other) {
	Collection<String>overlap = CollectionUtils.intersection(this.getCellBarcodes(), other.getCellBarcodes());
	if (!overlap.isEmpty()) {
		throw new IllegalArgumentException("The two matrixes have overlapping cell barcodes, this should not happen:" + overlap.toString());
	}

	// merge the cell barcodes.
	List <String> cellBarcodes = new ArrayList<>(this.getCellBarcodes());
	cellBarcodes.addAll(other.getCellBarcodes());
	List<String> allGenes = new ArrayList<> (CollectionUtils.union(this.getGenes(), other.getGenes()));
	Collections.sort(allGenes);

	int numCellsThis=this.getCellBarcodes().size();
	int numCellsOther=other.getCellBarcodes().size();
	CRSMatrix m = new CRSMatrix(allGenes.size(), cellBarcodes.size());

	for (int rowIdx=0; rowIdx<allGenes.size(); rowIdx++) {
		String g = allGenes.get(rowIdx);
		double [] thisExp = getExpressionWithNull(this.getExpression(g), 0, numCellsThis);
		double [] otherExp = getExpressionWithNull(other.getExpression(g), 0, numCellsOther);
		double [] expression  = ArrayUtils.addAll(thisExp, otherExp);
		for (int columnIdx=0; columnIdx<expression.length; columnIdx++)
			if (expression[columnIdx]!=0)
				m.set(rowIdx, columnIdx, expression[columnIdx]);
	}
	return (new DGEMatrix(cellBarcodes, allGenes, m));
}
 
Example 6
Source File: LanguageResourceTest.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void getLanguagesTest() {
    List<String> languages = languagesResource.getLanguages();
    List<String> supportedLanguages = PropertiesLoader.getSupportedLanguages();
    Assert.assertFalse(languages.isEmpty());
    Assert.assertEquals(supportedLanguages.size(),languages.size());
    Collection intersection = CollectionUtils.intersection(languages, supportedLanguages);
    Assert.assertEquals(supportedLanguages.size(),intersection.size());
}
 
Example 7
Source File: TimeZoneResourceTest.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void getTimeZonesTest() {
    List<String> timeZones = timeZoneResource.getTimeZones();
    Assert.assertFalse(timeZones.isEmpty());
    List<String> availableTimeZones = Arrays.asList(TimeZone.getAvailableIDs());
    Collection intersection = CollectionUtils.intersection(timeZones, availableTimeZones);
    Assert.assertEquals(timeZones.size(),intersection.size());
}
 
Example 8
Source File: ConsistencyExecutorImpl.java    From Thunder with Apache License 2.0 5 votes vote down vote up
private void consistBatch(String interfaze, List<ApplicationEntity> remoteList) throws Exception {
    List<ApplicationEntity> localList = cacheContainer.getConnectionCacheEntity().getApplicationEntityList(interfaze);
    if (!CollectionUtils.isEqualCollection(localList, remoteList)) {
        List<ApplicationEntity> intersectedList = (List<ApplicationEntity>) CollectionUtils.intersection(localList, remoteList);
        List<ApplicationEntity> onlineList = (List<ApplicationEntity>) CollectionUtils.subtract(remoteList, intersectedList);
        List<ApplicationEntity> offlineList = (List<ApplicationEntity>) CollectionUtils.subtract(localList, intersectedList);

        consistBatchClient(interfaze, onlineList, true);
        consistBatchClient(interfaze, offlineList, false);
    }
}
 
Example 9
Source File: JvueMethodAclVoter.java    From jvue-admin with MIT License 4 votes vote down vote up
@Override
public int vote(Authentication authentication, MethodInvocation invocation,
        Collection<ConfigAttribute> attributes) {
    JwtUserDetails jwtUser = null;
    // 1.判断是否为超级管理员,是的话直接放行
    if (authentication.getPrincipal() instanceof JwtUserDetails) {
        jwtUser = (JwtUserDetails) authentication.getPrincipal();
        if (jwtUser.getSuperUser() == JvueDataStatus.SUPER_USER_TRUE) {
            // 放行
            return ACCESS_GRANTED;
        }
    } else {
        return ACCESS_ABSTAIN;
    }

    // 1.判断URL对应的权限定义
    // >> arg1 FilterInvocation: URL: /module?page=0&pageSize=10
    // >> 如果不需要登录的话,直接放行
    Method method = invocation.getMethod();
    AclResc classResc = method.getDeclaringClass().getAnnotation(AclResc.class);
    AclResc methodAclResc = method.getAnnotation(AclResc.class);
    Integer apiCode = 0;
    if (classResc != null) {
        apiCode += classResc.id();
    }
    if (methodAclResc != null) {
        apiCode += methodAclResc.id();
    }
    
    if(apiCode > 0) {
        List<Integer> roles = jvueRoleService.getRolesByApi(apiCode);
        if (!roles.isEmpty()) {
            // 2.判断是否为超级管理员,是的话直接放行
            Collection<Integer> intersection =
                    CollectionUtils.intersection(roles, jwtUser.getRoles());
            if (intersection.isEmpty()) {
                // 没有匹配到角色
                return ACCESS_DENIED;
            } else {
                logger.debug("匹配到角色 {}", intersection);
                return ACCESS_GRANTED;
            }
        } else {
            return ACCESS_ABSTAIN;
        }
    } else {
        return ACCESS_ABSTAIN;
    }
}
 
Example 10
Source File: RoleAccessDecisionManager.java    From jvue-admin with MIT License 4 votes vote down vote up
@Override
    public void decide(Authentication authentication, Object arg1, Collection<ConfigAttribute> arg2)
            throws AccessDeniedException, InsufficientAuthenticationException {
        // TODO Auto-generated method stub
        logger.debug("arg0 {}, arg1 {}, arg2 {}", authentication, arg1, arg2);
        // 逻辑
        if (arg1 instanceof FilterInvocation) {
            // HTTP filter object
            FilterInvocation filterInvocation = (FilterInvocation) arg1;
            
//            // 1.判断是否为超级管理员,是的话直接放行
//            if (authentication.getPrincipal() instanceof JwtUserDetails) {
//                JwtUserDetails jwtUser = (JwtUserDetails) authentication.getPrincipal();
//                if (jwtUser.getSuperUser() == JvueDataStatus.SUPER_USER_TRUE) {
//                    // 放行
//                    logger.debug("SUPER_USER_TRUE");
//                    return ;
//                }
//            }
            
            // 1.判断URL对应的权限定义
            MultiMap<Integer, AclResource> resourcesMap =
                    hazelcastInstance.getMultiMap("acl-resource");
            // >> arg1 FilterInvocation: URL: /module?page=0&pageSize=10
            // >> 如果不需要登录的话,直接放行
            String requestUrl = filterInvocation.getRequestUrl();
            String requestMethod = filterInvocation.getRequest().getMethod();
            
            Integer apiCode = null;
            logger.debug("访问接口:{} {}", requestUrl, requestMethod);
            
            for (AclResource ar: resourcesMap.values()) {
                if (ar.getType() == AclResource.Type.METHOD) {
                    //pathHelper.
                    boolean isUrl = false;
                    boolean isMethod = false;
                    
                    logger.trace("判断接口:{} {} {}, {}", ar.getCode(), ar.getName(), ar.getPath(), ar.getPattern());

                    for (String path : ar.getPattern()) {
                        isUrl = pathMatcher.match(path, requestUrl);
                        if (isUrl) {
                            break;
                        }
                    }
                    if (isUrl) {
                        if (ar.getMethod() != null) {
                            for (String method: ar.getMethod()) {
                                if (Objects.equals(method, requestMethod)){
                                    isMethod = true;
                                    break;
                                }
                            }
                        } else {
                            isMethod = true;
                        }
                    }
                    
                    if (isUrl && isMethod) {
                        // 已匹配
                        apiCode = ar.getId();
                        logger.debug("已匹配接口:{} > {} {}", requestUrl, ar.getCode(), ar.getName());
                        break;
                    }
                }
            }
            
            if (apiCode != null ) {
                // 取对应的角色权限
                List<Integer> roles = jvueRoleService.getRolesByApi(apiCode);
                
                if (!roles.isEmpty()) {
                    // 2.判断是否为超级管理员,是的话直接放行
                    if (authentication.getPrincipal() instanceof JwtUserDetails) {
                        JwtUserDetails jwtUser = (JwtUserDetails) authentication.getPrincipal();
                        Collection<Integer> intersection =
                                CollectionUtils.intersection(roles, jwtUser.getRoles());
                        if (intersection.isEmpty()) {
                            // 没有匹配到角色
                            throw new AccessDeniedException("no role");
                        }

                    }
                }
            }
            
            // 处理 apiCode与角色匹配
            
            // 3.获取用户的角色,通过比对角色授予的API接口ID和AclResource里定义的ID,有匹配则放行
            
            // 4.上述以外,禁止调用
            // TODO throw new AccessDeniedException("no role");
        }
    }
 
Example 11
Source File: DGEMatrix.java    From Drop-seq with MIT License 4 votes vote down vote up
/**
 * Merge DGEs that have different genes in each DGE.  List of cells may overlap, or may not.
 * @return a new DGEMatrix that is the merge of this and other.
 */
private DGEMatrix mergeExpressionForCells(DGEMatrix other) {
	List<String> thisGenes = this.getGenes();
	List<String> otherGenes = other.getGenes();
	Collection<String> geneOverlap = CollectionUtils.intersection(thisGenes, otherGenes);
	if (!geneOverlap.isEmpty()) {
		throw new IllegalArgumentException("The two matrixes have overlapping genes, this should not happen:" +
				geneOverlap.toString());
	}
	List<String> allGenes = new ArrayList<> (thisGenes);
	CollectionUtils.addAll(allGenes, otherGenes);
	Collections.sort(allGenes);
	final ProgressLogger progressLogger = new ProgressLogger(log, 1000, "processed",
			String.format("genes of %d", allGenes.size()));
	// Determine which DGE has more cells.
	final DGEMatrix bigger;
	final DGEMatrix smaller;
	if (this.getCellBarcodes().size() >= other.getCellBarcodes().size()) {
		bigger = this;
		smaller = other;
	} else {
		bigger = other;
		smaller = this;
	}
	// Cells from bigger list go first, and then any that are in the smaller but not the bigger.
	final List<String> allCellBarcodes = new ArrayList<>(bigger.getCellBarcodes());
	// Create a map of the old to new index of columns in the DGE with fewer columns.
	final Map<Integer, Integer> smallerColumnMap = new HashMap<>();
	for (int column = 0; column < smaller.getCellBarcodes().size(); ++column) {
		final String cell = smaller.getCellBarcodes().get(column);
		int newColumn = allCellBarcodes.indexOf(cell);
		if (newColumn == -1) {
			newColumn = allCellBarcodes.size();
			allCellBarcodes.add(cell);
		}
		smallerColumnMap.put(column, newColumn);
	}
	CRSMatrix m = new CRSMatrix(allGenes.size(), allCellBarcodes.size());
	final Set<String> biggerGenesSet = new HashSet<>(bigger.getGenes());
	for (int i = 0; i < allGenes.size(); ++i) {
		final String gene = allGenes.get(i);
		org.la4j.Vector outVec;
		if (biggerGenesSet.contains(gene)) {
			outVec = bigger.expressionMatrix.getRow(bigger.geneMap.get(gene));
			// append zeroes as appropriate
			outVec = outVec.copyOfLength(allCellBarcodes.size());
		} else {
			final double[] primVec = new double[allCellBarcodes.size()];
			final VectorIterator it = smaller.expressionMatrix.getRow(smaller.geneMap.get(gene)).toSparseVector().nonZeroIterator();
			while (it.hasNext()) {
				final double val = it.next();
				final int newIndex = smallerColumnMap.get(it.index());
				primVec[newIndex] = val;
			}
			outVec = SparseVector.fromArray(primVec);
		}
		m.setRow(i, outVec);
		progressLogger.record(gene, i);
	}
	return (new DGEMatrix(allCellBarcodes, allGenes, m));
}
 
Example 12
Source File: CollectionUtilsSample.java    From spring-boot with Apache License 2.0 4 votes vote down vote up
/**
	 * @param args
	 */
	@SuppressWarnings({ "unchecked"})
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String[] arrayA = new String[] { "1", "2", "3", "3", "4", "5" };
		String[] arrayB = new String[] { "3", "4", "4", "5", "6", "7" };

		List<String> a = Arrays.asList(arrayA);
		List<String> b = Arrays.asList(arrayB);

		// === list
		//并集    
		Collection<String> l_union = CollectionUtils.union(a, b);
		//交集    
		Collection<String> l_intersection = CollectionUtils.intersection(a, b);
		//交集的补集    
		Collection<String> l_disjunction = CollectionUtils.disjunction(a, b);
		//集合相减
		Collection<String> l_subtract = CollectionUtils.subtract(a, b);

		Collections.sort((List<String>) l_union);
		Collections.sort((List<String>) l_intersection);
		Collections.sort((List<String>) l_disjunction);
		Collections.sort((List<String>) l_subtract);

		// === set

		String[] arrayC = new String[] { "1", "2", "3", "4", "5" };
		String[] arrayD = new String[] { "3", "4", "5", "6", "7" };

		TreeSet<String> c = new TreeSet<String>();
		CollectionUtils.addAll(c, arrayC);
		TreeSet<String> d = new TreeSet<String>();
		CollectionUtils.addAll(d, arrayD);
		
		//并集
		Collection<String> s_union = CollectionUtils.union(c, d);
		//交集
		Collection<String> s_intersection = CollectionUtils.intersection(c, d);
		//交集的补集
		Collection<String> s_disjunction = CollectionUtils.disjunction(c, d);
		//集合相减
		Collection<String> s_subtract = CollectionUtils.subtract(c, d);

//		Collections.sort((List<String>) s_union);
//		Collections.sort((List<String>) s_intersection);
//		Collections.sort((List<String>) s_disjunction);
//		Collections.sort((List<String>) s_subtract);

		System.out.println("List =========");
		System.out.println("A: " + ArrayUtils.toString(a.toArray()));
		System.out.println("B: " + ArrayUtils.toString(b.toArray()));
		System.out.println("--------------------------------------------");
		System.out.println("List: Union(A, B) 并集 : "
				+ ArrayUtils.toString(l_union.toArray()));
		System.out.println("List: Intersection(A, B) 交集 : "
				+ ArrayUtils.toString(l_intersection.toArray()));
		System.out.println("List: Disjunction(A, B) 交集的补集: "
				+ ArrayUtils.toString(l_disjunction.toArray()));
		System.out.println("List: Subtract(A, B) 集合相减  : "
				+ ArrayUtils.toString(l_subtract.toArray()));

		System.out.println("Set =========");
		System.out.println("C: " + ArrayUtils.toString(c.toArray()));
		System.out.println("D: " + ArrayUtils.toString(d.toArray()));
		System.out.println("--------------------------------------------");
		System.out.println("Set: Union(C, D) 并集 : "
				+ ArrayUtils.toString(s_union.toArray()));
		System.out.println("Set: Intersection(C, D) 交集 : "
				+ ArrayUtils.toString(s_intersection.toArray()));
		System.out.println("Set: Disjunction(C, D) 交集的补集: "
				+ ArrayUtils.toString(s_disjunction.toArray()));
		System.out.println("Set: Subtract(C, D) 集合相减  : "
				+ ArrayUtils.toString(s_subtract.toArray()));
	}
 
Example 13
Source File: CollectionUtilsGuideUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void givenTwoLists_whenIntersected_thenCheckSize() {
    Collection<Customer> intersection = CollectionUtils.intersection(list1, list3);
    assertTrue(intersection.size() == 2);
}