当前位置: 首页>>代码示例>>Java>>正文


Java Sets.difference方法代码示例

本文整理汇总了Java中com.google.common.collect.Sets.difference方法的典型用法代码示例。如果您正苦于以下问题:Java Sets.difference方法的具体用法?Java Sets.difference怎么用?Java Sets.difference使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.google.common.collect.Sets的用法示例。


在下文中一共展示了Sets.difference方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: formatConfiguration

import com.google.common.collect.Sets; //导入方法依赖的package包/类
static void formatConfiguration(StringBuilder sb, AttributeContainer fromConfigurationAttributes, AttributesSchema consumerSchema, List<ConfigurationMetadata> matches, Set<String> requestedAttributes, int maxConfLength, final String conf) {
    Optional<ConfigurationMetadata> match = Iterables.tryFind(matches, new Predicate<ConfigurationMetadata>() {
        @Override
        public boolean apply(ConfigurationMetadata input) {
            return conf.equals(input.getName());
        }
    });
    if (match.isPresent()) {
        AttributeContainer producerAttributes = match.get().getAttributes();
        Set<Attribute<?>> targetAttributes = producerAttributes.keySet();
        Set<String> targetAttributeNames = Sets.newTreeSet(Iterables.transform(targetAttributes, ATTRIBUTE_NAME));
        Set<Attribute<?>> allAttributes = Sets.union(fromConfigurationAttributes.keySet(), producerAttributes.keySet());
        Set<String> commonAttributes = Sets.intersection(requestedAttributes, targetAttributeNames);
        Set<String> consumerOnlyAttributes = Sets.difference(requestedAttributes, targetAttributeNames);
        sb.append("   ").append("- Configuration '").append(StringUtils.rightPad(conf + "'", maxConfLength + 1)).append(" :");
        List<Attribute<?>> sortedAttributes = Ordering.usingToString().sortedCopy(allAttributes);
        List<String> values = new ArrayList<String>(sortedAttributes.size());
        formatAttributes(sb, fromConfigurationAttributes, consumerSchema, producerAttributes, commonAttributes, consumerOnlyAttributes, sortedAttributes, values);
    }
}
 
开发者ID:lxxlxx888,项目名称:Reer,代码行数:21,代码来源:AmbiguousConfigurationSelectionException.java

示例2: getUserGroups

import com.google.common.collect.Sets; //导入方法依赖的package包/类
private Set<Group> getUserGroups(User user) {
    //get user's new group
    Set<Group> groupsForUser = findGroupsForUser(user.getPermission(), user.getRoles()).stream()
        .map(group -> {
            group.getUsers().add(user);
            groupDAO.save(group);
            return group;
        }).collect(Collectors.toSet());

    //remove user from old group
    Set<Group> oldGroups = Sets.difference(user.getGroups(), groupsForUser);
    oldGroups.stream()
        .filter(group -> group.getGroupType().equals(GroupType.PUBLIC))
        .map(group -> {
            group.getUsers().remove(user);
            groupDAO.save(group);
            return group;
        }).collect(Collectors.toSet());

    return groupsForUser;
}
 
开发者ID:tosinoni,项目名称:SECP,代码行数:22,代码来源:UserController.java

示例3: saveAssignedRoles

import com.google.common.collect.Sets; //导入方法依赖的package包/类
@Transactional
public void saveAssignedRoles(String userId, Set<Role> newRoles) {
    Set<Role> oldRoles = getAssignedRoles(userId);

    Sets.SetView<Role> removedRoles = Sets.difference(oldRoles, newRoles);
    Sets.SetView<Role> addedRoles = Sets.difference(newRoles, oldRoles);

    removedRoles.forEach(role -> {
        store.deleteRole(userId, role);
        logger.logEvent(new RoleDelEvent(Instant.now(), userId, role.getId(), role.getName()));
    });

    addedRoles.forEach(role -> {
        store.addRole(userId, role);
        logger.logEvent(new RoleAddEvent(Instant.now(), userId, role.getId(), role.getName()));
    });
}
 
开发者ID:LIBCAS,项目名称:ARCLib,代码行数:18,代码来源:AssignedRoleService.java

示例4: clusterChanged

import com.google.common.collect.Sets; //导入方法依赖的package包/类
@Override
public void clusterChanged(ClusterChangedEvent event) {
    if (!event.metaDataChanged()) {
        return;
    }

    Set<String> newCurrentSchemas = getNewCurrentSchemas(event.state().metaData());
    synchronized (schemas) {
        Sets.SetView<String> nonBuiltInSchemas = Sets.difference(schemas.keySet(), builtInSchemas.keySet());
        Set<String> deleted = Sets.difference(nonBuiltInSchemas, newCurrentSchemas).immutableCopy();
        Set<String> added = Sets.difference(newCurrentSchemas, schemas.keySet()).immutableCopy();

        for (String deletedSchema : deleted) {
            try {
                schemas.remove(deletedSchema).close();
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
            }
        }
        for (String addedSchema : added) {
            schemas.put(addedSchema, getCustomSchemaInfo(addedSchema));
        }
    }
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:25,代码来源:ReferenceInfos.java

示例5: updateTopics

import com.google.common.collect.Sets; //导入方法依赖的package包/类
private void updateTopics(Set<String> topicNames) {
    Set<String> currentTopics = topicsByName.keySet();
    Set<String> topicsToAdd = Sets.difference(topicNames, currentTopics);
    Set<String> topicsToRemove = Sets.difference(currentTopics, topicNames);

    topicsToAdd.stream()
            .filter(topicName -> !topicName.equals("__consumer_offsets"))
            .forEach(topicName -> {
                try {
                    String partitionsPath = "/brokers/topics/" + topicName + "/partitions";
                    zkClient.waitUntilExists(partitionsPath, TimeUnit.SECONDS, 5);
                    topicsByName.put(topicName, new KafkaTopic(topicName, zkClient.getChildren(partitionsPath).size()));
                    log.info("Topic added: [{}]", topicName);
                } catch (Exception e) {
                    log.error("Exception fetching info for topic [{}]: {}", topicName, e.getMessage(), e);
                }
            });

    topicsToRemove.forEach(topicName -> {
        topicsByName.remove(topicName);
        log.info("Topic deleted: [{}]", topicName);
    });
}
 
开发者ID:enthusiast94,项目名称:kafka-visualizer,代码行数:24,代码来源:KafkaTopicsTracker.java

示例6: ClusterMetadataDiff

import com.google.common.collect.Sets; //导入方法依赖的package包/类
public ClusterMetadataDiff(ClusterMetadata oldValue, ClusterMetadata newValue) {
    this.oldValue = oldValue;
    this.newValue = newValue;

    Set<ControllerNode> currentNodeSet = oldValue == null
            ? ImmutableSet.of() : ImmutableSet.copyOf(oldValue.getNodes());
    Set<ControllerNode> newNodeSet = newValue == null
            ? ImmutableSet.of() : ImmutableSet.copyOf(newValue.getNodes());
    nodesAdded = Sets.difference(newNodeSet, currentNodeSet);
    nodesRemoved = Sets.difference(currentNodeSet, newNodeSet)
                       .stream()
                       .map(ControllerNode::id)
                       .collect(Collectors.toSet());
}
 
开发者ID:shlee89,项目名称:athena,代码行数:15,代码来源:ClusterMetadataDiff.java

示例7: balanceRolesUsingRegions

import com.google.common.collect.Sets; //导入方法依赖的package包/类
/**
 * Balances the nodes considering Region information.
 *
 * @param allControllerDevices controller nodes to devices map
 * @return true: nodes balanced; false: nodes not balanced
 */
private boolean balanceRolesUsingRegions(Map<ControllerNode, Set<DeviceId>> allControllerDevices) {
    Set<Region> regions = regionService.getRegions();
    if (regions.isEmpty()) {
        return false; // no balancing was done using regions.
    }

    // handle nodes belonging to regions
    Set<ControllerNode> nodesInRegions = Sets.newHashSet();
    for (Region region : regions) {
        Map<ControllerNode, Set<DeviceId>> activeRegionControllers =
                balanceRolesInRegion(region, allControllerDevices);
        nodesInRegions.addAll(activeRegionControllers.keySet());
    }

    // handle nodes not belonging to any region
    Set<ControllerNode> nodesNotInRegions = Sets.difference(allControllerDevices.keySet(), nodesInRegions);
    if (!nodesNotInRegions.isEmpty()) {
        int deviceCount = 0;
        Map<ControllerNode, Set<DeviceId>> controllerDevicesNotInRegions = new HashMap<>();
        for (ControllerNode controllerNode: nodesNotInRegions) {
            controllerDevicesNotInRegions.put(controllerNode, allControllerDevices.get(controllerNode));
            deviceCount += allControllerDevices.get(controllerNode).size();
        }
        // Now re-balance the buckets until they are roughly even.
        List<CompletableFuture<Void>> balanceBucketsFutures =
                balanceControllerNodes(controllerDevicesNotInRegions, deviceCount);

        CompletableFuture<Void> balanceRolesFuture = CompletableFuture.allOf(
                balanceBucketsFutures.toArray(new CompletableFuture[balanceBucketsFutures.size()]));

        Futures.getUnchecked(balanceRolesFuture);
    }
    return true; // balancing was done using regions.
}
 
开发者ID:shlee89,项目名称:athena,代码行数:41,代码来源:MastershipManager.java

示例8: asNodeTree

import com.google.common.collect.Sets; //导入方法依赖的package包/类
@Lazy
protected ImmutableList<Node> asNodeTree() {
	ImmutableMap<String, String> childParentMap = childParentMap();
	SetView<String> roots = Sets.difference(relation().keySet(), childParentMap.keySet());
	return roots.stream()
		.map(s -> nodeOf(s, relation()))
		.collect(ImmutableList.toImmutableList());
}
 
开发者ID:flapdoodle-oss,项目名称:de.flapdoodle.solid,代码行数:9,代码来源:Tree.java

示例9: checkLinkingValidity

import com.google.common.collect.Sets; //导入方法依赖的package包/类
private void checkLinkingValidity(final Symbol docID, final ArgumentOutput docOutput,
    final Optional<LinkingStore> linkingStore) throws IOException {
  final Optional<ResponseLinking> responseLinking = linkingStore.get().read(docOutput);
  if (!responseLinking.isPresent()) {
    throw new RuntimeException("Linking missing for " + docID);
  }
  final Set<Response> allLinkedResponses = ImmutableSet
      .copyOf(Iterables.concat(responseLinking.get().responseSets()));
  final Set<Response> nonGenericArgumentResponses = Sets
      .filter(docOutput.responses(), NOT_GENERIC);
  if (!allLinkedResponses.equals(nonGenericArgumentResponses)) {
    final StringBuilder msg = new StringBuilder();
    msg.append(
        "The set of linked responses should exactly equal the set of non-generic argument responses. However, ");
    final Set<Response> linkingOnly =
        Sets.difference(allLinkedResponses, nonGenericArgumentResponses);
    final Set<Response> argumentOnly =
        Sets.difference(nonGenericArgumentResponses, allLinkedResponses);

    if (!linkingOnly.isEmpty()) {
      msg.append("\nThe following are in the linking only:\n ")
          .append(StringUtils.NewlineJoiner.join(linkingOnly));
    }
    if (!argumentOnly.isEmpty()) {
      msg.append("\nThe following are in the argument output only:\n")
          .append(StringUtils.NewlineJoiner.join(argumentOnly));
    }
    throw new RuntimeException(msg.toString());
  }
  if (!linkingValidator.validate(responseLinking.get())) {
    throw new RuntimeException(String.format("Validation failed for %s with validator %s", docID,
        linkingValidator.getClass().toString()));
  }
}
 
开发者ID:isi-nlp,项目名称:tac-kbp-eal,代码行数:35,代码来源:ValidateSystemOutput.java

示例10: assertDocsAreContained

import com.google.common.collect.Sets; //导入方法依赖的package包/类
private void assertDocsAreContained(Set<Symbol> docsInStore,
    Set<Symbol> docsInCorpus, String storeType) throws IOException {
  final Set<Symbol> extraDocs = Sets.difference(docsInStore, docsInCorpus);
  if (!extraDocs.isEmpty()) {
    throw new RuntimeException(
        String.format(
            "The " + storeType
                + " store contains the following documents which are not in the target corpus: %s",
            extraDocs));
  }
}
 
开发者ID:isi-nlp,项目名称:tac-kbp-eal,代码行数:12,代码来源:ValidateSystemOutput.java

示例11: assertLinkingSubsetOfAnswerKey

import com.google.common.collect.Sets; //导入方法依赖的package包/类
private void assertLinkingSubsetOfAnswerKey(ResponseLinking responseLinking, AnswerKey answerKey)
    throws InconsistentLinkingException {
  final Set<Response> inLinkingButNotKey =
      Sets.difference(responseLinking.allResponses(), answerKey.allResponses());
  if (!inLinkingButNotKey.isEmpty()) {
    throw new InconsistentLinkingException("Response linking should be a subset of answer key."
        + " In linking only:\n" + inLinkingButNotKey);
  }
}
 
开发者ID:isi-nlp,项目名称:tac-kbp-eal,代码行数:10,代码来源:ExactMatchEventArgumentLinkingAligner.java

示例12: copyFallingBackTo

import com.google.common.collect.Sets; //导入方法依赖的package包/类
/**
 * Takes this AnswerKey as ground truth, and takes unannotated or assessed Responses in fallback
 * and adds them to the AnswerKey.
 *
 * If the CAS for an AssessedResponse is known, prefer that CAS to the CAS in fallback.
 *
 * Does not handle the case where the fallback AnswerKey has an Assessment that this AnswerKey
 * does not.
 */
public AnswerKey copyFallingBackTo(AnswerKey fallback) {
  final Builder ret = modifiedCopyBuilder();

  final ImmutableMap<String, Response> unannotatedHere = Maps.uniqueIndex(unannotatedResponses(),
      ResponseFunctions.uniqueIdentifier());
  final ImmutableMap<String, AssessedResponse> idToAssessedHere =
      Maps.uniqueIndex(annotatedResponses(),
          Functions.compose(ResponseFunctions.uniqueIdentifier(),
              AssessedResponseFunctions.response()));
  final Set<String> idsHere = Sets.union(unannotatedHere.keySet(), idToAssessedHere.keySet());

  final ImmutableMap<String, Response> unannotatedThere = Maps.uniqueIndex(
      fallback.unannotatedResponses(), ResponseFunctions.uniqueIdentifier());
  final ImmutableMap<String, AssessedResponse> idToAssessedThere =
      Maps.uniqueIndex(fallback.annotatedResponses(),
          Functions.compose(ResponseFunctions.uniqueIdentifier(),
              AssessedResponseFunctions.response()));
  final Set<String> idsThere = Sets.union(unannotatedThere.keySet(), idToAssessedThere.keySet());

  final Set<String> idsOnlyInFallback = Sets.difference(idsThere, idsHere);
  for (final String id : idsOnlyInFallback) {
    if (unannotatedThere.containsKey(id)) {
      ret.addUnannotated(unannotatedThere.get(id));
    }
    if (idToAssessedThere.containsKey(id)) {
      final AssessedResponse r = idToAssessedThere.get(id);
      final int CASGroup;
      if (corefAnnotation().CASesToIDs().containsKey(r.response().canonicalArgument())) {
        CASGroup = corefAnnotation().CASesToIDs().get(r.response().canonicalArgument());
      } else {
        CASGroup = fallback.corefAnnotation().CASesToIDs().get(r.response().canonicalArgument());
      }
      ret.addAnnotated(r, CASGroup);
    }
  }
  return ret.build();
}
 
开发者ID:isi-nlp,项目名称:tac-kbp-eal,代码行数:47,代码来源:AnswerKey.java

示例13: register

import com.google.common.collect.Sets; //导入方法依赖的package包/类
boolean register(DiscreteResourceId key, List<ContinuousResource> values) {
    // short-circuit: receiving empty resource is regarded as success
    if (values.isEmpty()) {
        return true;
    }

    Set<ContinuousResource> requested = new LinkedHashSet<>(values);
    Set<ContinuousResource> oldValues = childMap.putIfAbsent(key, requested);
    if (oldValues == null) {
        return true;
    }

    Set<ContinuousResource> addedValues = Sets.difference(requested, oldValues);
    // no new value, then no-op
    if (addedValues.isEmpty()) {
        // don't write to map because all values are already stored
        return true;
    }

    Set<ContinuousResourceId> addedIds = addedValues.stream()
            .map(ContinuousResource::id)
            .collect(Collectors.toSet());
    // if the value is not found but the same ID is found
    // (this happens only when being continuous resource)
    if (oldValues.stream().anyMatch(x -> addedIds.contains(x.id()))) {
        // no-op, but indicating failure (reject the request)
        return false;
    }
    Set<ContinuousResource> newValues = new LinkedHashSet<>(oldValues);
    newValues.addAll(addedValues);
    return childMap.replace(key, oldValues, newValues);
}
 
开发者ID:shlee89,项目名称:athena,代码行数:33,代码来源:TransactionalContinuousResourceSubStore.java

示例14: testSampleTaskGroupSanity

import com.google.common.collect.Sets; //导入方法依赖的package包/类
@Test
public void testSampleTaskGroupSanity() {
    // Prepare sample group
    //
    /**
     *
     *   |------------------->B------------|
     *   |                                 |
     *   |                                 ↓
     *   F            ------->C----------->A
     *   |            |                    ^
     *   |            |                    |
     *   |------------>E                   |
     *                |                    |
     *                |                    |
     *                ------->D-------------
     */
    final List<String> groupItems = new ArrayList<>();
    TaskGroup group = createSampleTaskGroup("A", "B",
            "C", "D",
            "E", "F",
            groupItems);

    // Invocation of group should invoke all the tasks
    //
    group.invokeAsync(group.newInvocationContext())
            .subscribe(new Action1<Indexable>() {
                @Override
                public void call(Indexable value) {
                    StringIndexable stringIndexable = toStringIndexable(value);
                    Assert.assertTrue(groupItems.contains(stringIndexable.str()));
                    groupItems.remove(stringIndexable.str());
                }
            });

    Assert.assertEquals(0, groupItems.size());

    Map<String, Set<String>> shouldNotSee = new HashMap<>();

    // NotSeen entries for group-1
    shouldNotSee.put("A", new HashSet<String>());
    shouldNotSee.get("A").addAll(Arrays.asList(new String[] {"B", "C", "D", "E", "F"}));

    shouldNotSee.put("B", new HashSet<String>());
    shouldNotSee.get("B").addAll(Arrays.asList(new String[] {"F"}));

    shouldNotSee.put("C", new HashSet<String>());
    shouldNotSee.get("C").addAll(Arrays.asList(new String[] {"E", "F"}));

    shouldNotSee.put("D", new HashSet<String>());
    shouldNotSee.get("D").addAll(Arrays.asList(new String[] {"E", "F"}));

    shouldNotSee.put("E", new HashSet<String>());
    shouldNotSee.get("E").addAll(Arrays.asList(new String[] {"F"}));

    shouldNotSee.put("F", new HashSet<String>());
    shouldNotSee.get("F").addAll(Arrays.asList(new String[] {}));

    Set<String> seen = new HashSet<>();
    // Test invocation order for group
    //
    group.prepareForEnumeration();
    for (TaskGroupEntry<TaskItem> entry = group.getNext(); entry != null; entry = group.getNext()) {
        Sets.SetView<String> common = Sets.intersection(shouldNotSee.get(entry.key()), seen);
        if (common.size() > 0) {
            Assert.assertTrue("The entries " + common + " must be emitted before " + entry.key(), false);
        }
        seen.add(entry.key());
        group.reportCompletion(entry);
    }

    Assert.assertEquals(6, seen.size()); // 1 groups with 6 nodes
    Set<String> expectedToSee = new HashSet<>();
    expectedToSee.addAll(Arrays.asList(new String[]  {"A", "B", "C", "D", "E", "F"}));
    Sets.SetView<String> diff = Sets.difference(seen, expectedToSee);
    Assert.assertEquals(0, diff.size());
}
 
开发者ID:Azure,项目名称:azure-libraries-for-java,代码行数:78,代码来源:ProxyTaskGroupTests.java

示例15: testDiff

import com.google.common.collect.Sets; //导入方法依赖的package包/类
@Test
public void testDiff() {
	Set<Integer> diff = Sets.difference(ALL_WORKER_IDS, Sets.newHashSet(0, 1, 2, 3, 4));
	System.out.println(diff.stream().findFirst().get());
}
 
开发者ID:mm23504570,项目名称:snowflake,代码行数:6,代码来源:SnowflakeServerTest.java


注:本文中的com.google.common.collect.Sets.difference方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。