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

The following examples show how to use org.apache.commons.collections4.CollectionUtils#subtract() . 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: ConsulNamingService.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    while (!stopWatch) {
        Response<List<HealthService>> response = lookupHealthService(serviceName, lastConsulIndex);
        Long currentIndex = response.getConsulIndex();
        if (currentIndex != null && currentIndex > lastConsulIndex) {
            List<ServiceInstance> currentInstances = convert(response);
            Collection<ServiceInstance> addList = CollectionUtils.subtract(
                    currentInstances, lastInstances);
            Collection<ServiceInstance> deleteList = CollectionUtils.subtract(
                    lastInstances, currentInstances);
            listener.notify(addList, deleteList);
            lastInstances = currentInstances;
            lastConsulIndex = currentIndex;
        }
    }
}
 
Example 2
Source File: RangerSecurityServiceConnector.java    From egeria with Apache License 2.0 6 votes vote down vote up
private void syncAssociations(Map<String, Set<String>> tagToResource, Map<String, Set<String>> existingMapping) {
    Map<String, List<String>> newMappings = new HashMap<>();
    Map<String, List<String>> outdatedMapping = new HashMap<>();

    for (Map.Entry<String, Set<String>> tags : tagToResource.entrySet()) {
        Set<String> existingTags = existingMapping.get(tags.getKey());
        if (existingTags == null) {
            newMappings.put(tags.getKey(), new ArrayList<>(tags.getValue()));
            continue;
        }

        Collection<String> newlyAdded = CollectionUtils.subtract(tags.getValue(), existingTags);
        if (!newlyAdded.isEmpty()) {
            newMappings.put(tags.getKey(), (List<String>) newlyAdded);
        }

        Collection<String> outdatedTags = CollectionUtils.subtract(existingTags, tags.getValue());
        if (!outdatedTags.isEmpty()) {
            outdatedMapping.put(tags.getKey(), (List<String>) outdatedTags);
        }
    }

    newMappings.forEach((resourceId, tags) -> tags.forEach(tagId -> createAssociationResourceToSecurityTag(resourceId, tagId)));
    outdatedMapping.forEach((resourceId, tags) -> tags.forEach(tag -> deleteAssociationResourceToSecurityTagBasedOnIds(resourceId, tag)));
}
 
Example 3
Source File: CommonsExample.java    From pragmatic-java-engineer with GNU General Public License v3.0 6 votes vote down vote up
public static void collections() {
    List<String> list = Lists.newArrayList();
    List<String> list2 = Lists.newArrayList();

    if (CollectionUtils.isNotEmpty(list)) {
        CollectionUtils.subtract(list, list2);
        CollectionUtils.subtract(list, list2);
        CollectionUtils.retainAll(list, list2);
    }

    OrderedMap map = new LinkedMap();
    map.put("1", "1");
    map.put("2", "2");
    map.put("3", "3");
    map.firstKey();
    map.nextKey("1");
}
 
Example 4
Source File: SystemInputDocReader.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns the set of unexpected property names, ordered by increasing line number.
 */
private List<String> getPropertiesUnexpected( Map<String,Integer> expected, final Map<String,Integer> actual)
  {
  List<String> unexpected = new ArrayList<String>( CollectionUtils.subtract( actual.keySet(), expected.keySet()));
  Collections.sort
    ( unexpected,
      new Comparator<String>()
        {
        public int compare( String property1, String property2)
          {
          int line1 = actual.get( property1);
          int line2 = actual.get( property2);
          return line1 - line2;
          }
        });
  return unexpected;
  }
 
Example 5
Source File: RandomStrategy.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public CommunicationClient selectInstance(
        Request request,
        List<CommunicationClient> instances,
        Set<CommunicationClient> selectedInstances) {
    if (CollectionUtils.isEmpty(instances)) {
        return null;
    }

    Collection<CommunicationClient> toBeSelectedInstances = null;
    if (selectedInstances == null) {
        toBeSelectedInstances = instances;
    } else {
        toBeSelectedInstances = CollectionUtils.subtract(instances, selectedInstances);
    }

    int instanceNum = toBeSelectedInstances.size();
    if (instanceNum == 0) {
        toBeSelectedInstances = instances;
        instanceNum = toBeSelectedInstances.size();
    }

    if (instanceNum == 0) {
        return null;
    }
    int index = getRandomInt(instanceNum);
    CommunicationClient serviceInstance = toBeSelectedInstances.toArray(new CommunicationClient[0])[index];
    return serviceInstance;
}
 
Example 6
Source File: SystemInputs.java    From tcases with MIT License 5 votes vote down vote up
/**
 * For every property in the given function input definition that is defined but never referenced,
 * maps the property to the variable value definitions that contribute it.
 */
public static Map<String,Collection<VarBindingDef>> getPropertiesUnused( FunctionInputDef function)
  {
  Map<String,Collection<VarBindingDef>> sources = getPropertySources( function);
  Collection<String> unused = CollectionUtils.subtract( sources.keySet(), getPropertyReferences( function).keySet());

  return
    sources.entrySet().stream()
    .filter( entry -> unused.contains( entry.getKey()))
    .collect( toMap( entry -> entry.getKey(), entry -> entry.getValue()));
  }
 
Example 7
Source File: SystemInputs.java    From tcases with MIT License 5 votes vote down vote up
/**
 * For every property in the given function input definition that is referenced but never defined,
 * maps the property to the conditional elements that reference it.
 */
public static Map<String,Collection<IConditional>> getPropertiesUndefined( FunctionInputDef function)
  {
  Map<String,Collection<IConditional>> refs = getPropertyReferences( function);
  Collection<String> undefined = CollectionUtils.subtract( refs.keySet(), getPropertySources( function).keySet());

  return
    refs.entrySet().stream()
    .filter( entry -> undefined.contains( entry.getKey()))
    .collect( toMap( entry -> entry.getKey(), entry -> entry.getValue()));
  }
 
Example 8
Source File: Asserts.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Reports a failure if the actual Collection contains a different set of values than the expected Collection.
 *
 * @deprecated Replace using <CODE>Composites::containsMembers</CODE> from <A href="https://github.com/Cornutum/hamcrest-composites">Hamcrest Composites</A>.
 */
@Deprecated
public static <T> void assertSetsEqual( String label, Collection<T> expected, Collection<T> actual, Matcher<T> matcher)
  {
  if( Matcher.matchable( label, expected, actual))
    {
    Collection<T> unexpected = CollectionUtils.subtract( actual, expected);
    Collection<T> missing = CollectionUtils.subtract( expected, actual);

    if( !(unexpected.isEmpty() && missing.isEmpty()))
      {
      StringBuilder msg = new StringBuilder();

      msg.append( label);
      if( !missing.isEmpty())
        {
        msg.append( ", missing=").append( '[').append( StringUtils.join( missing, ',')).append( ']');
        }
      if( !unexpected.isEmpty())
        {
        msg.append( ", unexpected=").append( '[').append( StringUtils.join( unexpected, ',')).append( ']');
        }

      fail( msg.toString());
      }

    if( matcher != null)
      {
      Map<T,T> actualMembers = mapSelf( actual);
      for( T member : expected)
        {
        assertMatches( label, member, actualMembers.get( member), matcher);
        }
      }
    }
  }
 
Example 9
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 10
Source File: ScopedController.java    From ontopia with Apache License 2.0 5 votes vote down vote up
public void setScope(ScopedIF scoped, Collection<Topic> scope) {
	if (scope != null) {
		Collection<TopicIF> newScope = new HashSet<>(scope.size());
		for (Topic t : scope) {
			TopicIF resolved = topic.resolve(scoped.getTopicMap(), t);
			newScope.add(resolved);
			scoped.addTheme(resolved);
		}
		
		for (TopicIF remove : CollectionUtils.subtract(scoped.getScope(), newScope)) {
			scoped.removeTheme(remove);
		}
	}
}
 
Example 11
Source File: JvueUserServiceImpl.java    From jvue-admin with MIT License 4 votes vote down vote up
@Override
    @CacheEvict(value = "JwtUserDetailsService", key = "#result.username")
    public JvueUser updateRoles(Long id, List<Integer> roles) {
        Assert.notNull(id, "用户ID不能为空");
        JvueUserRole userRole = new JvueUserRole();
        userRole.setUserId(id);
        List<JvueUserRole> userRoles = userRoleMapper.select(userRole);
        
        Collection<Integer> deleds;
        Collection<Integer> addeds;
        
        List<Integer> existes = userRoles.stream().map(r -> r.getRoleId()).collect(Collectors.toList());
        
        if (existes != null) {
            if (roles != null && roles.size() > 0) {
                deleds = CollectionUtils.subtract(existes, roles);
                addeds = CollectionUtils.subtract(roles, existes);
            } else {
                // 删除所有
                userRoleMapper.delete(userRole);
                deleds = null;
                addeds = null;
            }
        } else {
            deleds = null;
            addeds = roles;
        }
        
        if (deleds != null && deleds.size() > 0) {
//            SearchCriteria<UserRole> searchCriteria = new SearchCriteria<>();
//            searchCriteria.add(JpaRestrictions.eq("userId", id, false));
//            searchCriteria.add(JpaRestrictions.in("roleId", deleds, false));
//            List<UserRole> dRoles = userRoleMapper.findAll(searchCriteria);
//            userRoleMapper.deleteAll(dRoles);
            
            Example example = new Example.Builder(JvueUserRole.class).where(
                    WeekendSqls.<JvueUserRole>custom().andEqualTo(JvueUserRole::getUserId, id).andIn(JvueUserRole::getRoleId, deleds))
                    .build();
            
            userRoleMapper.deleteByExample(example);
        }
        
        if (addeds != null && addeds.size() > 0) {
            
            for (Integer roleId: addeds) {
                JvueUserRole role = new JvueUserRole();
                role.setUserId(id);
                role.setRoleId(roleId);
                userRoleMapper.insertSelective(role);
            }
        }
        
        return getOne(id);
    }
 
Example 12
Source File: RangerSecurityServiceConnector.java    From egeria with Apache License 2.0 4 votes vote down vote up
private void syncResources(List<RangerServiceResource> resources, List<RangerServiceResource> existingResources) {
    Collection<RangerServiceResource> newResources = CollectionUtils.subtract(resources, existingResources);
    newResources.forEach(this::createRangerServiceResource);
}
 
Example 13
Source File: RangerSecurityServiceConnector.java    From egeria with Apache License 2.0 4 votes vote down vote up
private void syncTags(Set<RangerTag> tags, Set<RangerTag> rangerExistingTags) {
    Collection<RangerTag> newTags = CollectionUtils.subtract(tags, rangerExistingTags);
    newTags.forEach(this::createRangerTag);
}
 
Example 14
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 15
Source File: CollectionUtilsGuideUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void givenTwoLists_whenSubtracted_thenCheckElementNotPresentInA() {
    Collection<Customer> result = CollectionUtils.subtract(list1, list3);
    assertFalse(result.contains(customer1));
}
 
Example 16
Source File: DependencyMaterialUpdateNotifier.java    From gocd with Apache License 2.0 3 votes vote down vote up
private void scheduleRecentlyAddedMaterialsForUpdate() {
    Collection<Material> materialsBeforeConfigChange = dependencyMaterials.values();

    this.dependencyMaterials = dependencyMaterials();

    Collection<Material> materialsAfterConfigChange = dependencyMaterials.values();

    Collection newMaterials = CollectionUtils.subtract(materialsAfterConfigChange, materialsBeforeConfigChange);

    for (Object material : newMaterials) {
        updateMaterial((Material) material);
    }
}