Java Code Examples for java.util.List#retainAll()
The following examples show how to use
java.util.List#retainAll() .
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: UserDispersingPlanner.java From cloudstack with Apache License 2.0 | 6 votes |
/** * This method should reorder the given list of Pod Ids by applying any necessary heuristic * for this planner * For UserDispersingPlanner we need to order the pods by considering the number of VMs for this account * @return List<Long> ordered list of Pod Ids */ @Override protected List<Long> reorderPods(Pair<List<Long>, Map<Long, Double>> podCapacityInfo, VirtualMachineProfile vmProfile, DeploymentPlan plan) { List<Long> podIdsByCapacity = podCapacityInfo.first(); if (vmProfile.getOwner() == null) { return podIdsByCapacity; } long accountId = vmProfile.getOwner().getAccountId(); Pair<List<Long>, Map<Long, Double>> podIdsVmCountInfo = listPodsByUserDispersion(plan.getDataCenterId(), accountId); //now we have 2 pod lists - one ordered by capacity and the other by number of VMs for this account //need to apply weights to these to find the correct ordering to follow if (_userDispersionWeight == 1.0f) { List<Long> podIds = podIdsVmCountInfo.first(); podIds.retainAll(podIdsByCapacity); return podIds; } else { //apply weights to the two lists return orderByApplyingWeights(podCapacityInfo, podIdsVmCountInfo, accountId); } }
Example 2
Source File: JoinedTest.java From cactoos with MIT License | 6 votes |
@Test public void retainAll() { final List<String> joined = new Joined<String>( new ListOf<>(JoinedTest.LITERAL_ONE), new ListOf<>( JoinedTest.LITERAL_TWO, JoinedTest.LITERAL_THREE ) ); joined.retainAll( new ListOf<>( JoinedTest.LITERAL_TWO, JoinedTest.LITERAL_THREE ) ); new Assertion<>( "must be able to retain all", joined, new IsEqual<>( new ListOf<>( JoinedTest.LITERAL_TWO, JoinedTest.LITERAL_THREE ) ) ).affirm(); }
Example 3
Source File: DeadCodeChecker.java From basicv2 with The Unlicense | 6 votes |
public static PCode removeDeadCode(PCode code) { Logger.log("Detecting dead code..."); List<Integer> nums = code.getLineNumbers(); Map<Integer, Line> lineMap = code.getLines(); Set<Integer> used = new HashSet<>(); if (nums.isEmpty()) { return code; } addDatas(lineMap, used); trackCode(nums, lineMap, used, 0); Logger.log((nums.size() - used.size() + " lines of dead code removed!")); for (Integer num : nums) { if (!used.contains(num)) { lineMap.remove(num); //Logger.log("Line " + num + " contains dead code!"); } } nums.retainAll(used); return new PCode(nums, lineMap); }
Example 4
Source File: BulkExtractMongoDA.java From secure-data-service with Apache License 2.0 | 5 votes |
@SuppressWarnings({ "unchecked" }) private static List<String> getAuthorizedTenantEdorgs(Entity app, List<String> tenantEdorgs) { List<String> authorizedTenantEdorgs = (List<String>) app.getBody().get(AUTH_EDORGS_FIELD); authorizedTenantEdorgs.retainAll(tenantEdorgs); return authorizedTenantEdorgs; }
Example 5
Source File: DistroxService.java From cloudbreak with Apache License 2.0 | 5 votes |
private AttemptResult<Void> evaluateResult(List<String> pollingCrn, List<String> remaining, List<AttemptResult<Void>> results) { Optional<AttemptResult<Void>> error = results.stream().filter(it -> it.getState() == AttemptState.BREAK).findFirst(); if (error.isPresent()) { return error.get(); } long count = results.stream().filter(it -> it.getState() == AttemptState.CONTINUE).count(); if (count > 0) { return AttemptResults.justContinue(); } pollingCrn.retainAll(remaining); return AttemptResults.finishWith(null); }
Example 6
Source File: PropertyList.java From syncope with Apache License 2.0 | 5 votes |
@Override public boolean retainAll(final Collection<?> c) { final List<String> list = getEnumValuesAsList(getValues()); final boolean res = list.retainAll(c); setValues(list); return res; }
Example 7
Source File: ProfileInfoResource.java From jhipster-microservices-example with Apache License 2.0 | 5 votes |
private String getRibbonEnv(String[] activeProfiles) { String[] displayOnActiveProfiles = jHipsterProperties.getRibbon().getDisplayOnActiveProfiles(); if (displayOnActiveProfiles == null) { return null; } List<String> ribbonProfiles = new ArrayList<>(Arrays.asList(displayOnActiveProfiles)); List<String> springBootProfiles = Arrays.asList(activeProfiles); ribbonProfiles.retainAll(springBootProfiles); if (!ribbonProfiles.isEmpty()) { return ribbonProfiles.get(0); } return null; }
Example 8
Source File: DatahubPollerProvider.java From cloudbreak with Apache License 2.0 | 5 votes |
public AttemptMaker<Void> stopDatahubClustersPoller(List<String> datahubCrns, Long envId) { List<String> mutableCrnList = new ArrayList<>(datahubCrns); return () -> { List<String> remaining = new ArrayList<>(); List<AttemptResult<Void>> results = collectDatahubStopResults(mutableCrnList, remaining, envId); mutableCrnList.retainAll(remaining); return clusterPollerResultEvaluator.evaluateResult(results); }; }
Example 9
Source File: ProfileInfoResource.java From cubeai with Apache License 2.0 | 5 votes |
private String getRibbonEnv(String[] activeProfiles) { String[] displayOnActiveProfiles = jHipsterProperties.getRibbon().getDisplayOnActiveProfiles(); if (displayOnActiveProfiles == null) { return null; } List<String> ribbonProfiles = new ArrayList<>(Arrays.asList(displayOnActiveProfiles)); List<String> springBootProfiles = Arrays.asList(activeProfiles); ribbonProfiles.retainAll(springBootProfiles); if (!ribbonProfiles.isEmpty()) { return ribbonProfiles.get(0); } return null; }
Example 10
Source File: PollListManagerImpl.java From sakai with Educational Community License v2.0 | 5 votes |
public List<Poll> findAllPollsForUserAndSitesAndPermission(String userId, String[] siteIds, String permissionConstant) { if (userId == null || permissionConstant == null) { throw new IllegalArgumentException("userId and permissionConstant must be set"); } List<Poll> polls = null; // get all allowed sites for this user List<String> allowedSites = externalLogic.getSitesForUser(userId, permissionConstant); if (allowedSites.isEmpty()) { // no sites to search so EXIT here return new ArrayList<>(); } else { if (siteIds != null && siteIds.length > 0) { List<String> requestedSiteIds = Arrays.asList(siteIds); // filter down to just the requested ones allowedSites.retainAll(requestedSiteIds); } String[] siteIdsToSearch = allowedSites.toArray(new String[0]); Search search = new Search(); if (siteIdsToSearch.length > 0) { search.addRestriction(new Restriction("siteId", siteIdsToSearch)); } if (PollListManager.PERMISSION_VOTE.equals(permissionConstant)) { // limit to polls which are open Date now = new Date(); search.addRestriction(new Restriction("voteOpen", now, Restriction.LESS)); search.addRestriction(new Restriction("voteClose", now, Restriction.GREATER)); } else { // show all polls } search.addOrder(new Order("creationDate")); polls = dao.findBySearch(Poll.class, search); } if (polls == null) { polls = new ArrayList<Poll>(); } return polls; }
Example 11
Source File: PinotHelixResourceManager.java From incubator-pinot with Apache License 2.0 | 5 votes |
/** * Computes the server nodes that are untagged and free to be used. * @return List of untagged online server instances. */ public List<String> getOnlineUnTaggedServerInstanceList() { List<String> instanceList = HelixHelper.getInstancesWithTag(_helixZkManager, Helix.UNTAGGED_SERVER_INSTANCE); List<String> liveInstances = _helixDataAccessor.getChildNames(_keyBuilder.liveInstances()); instanceList.retainAll(liveInstances); return instanceList; }
Example 12
Source File: FirstFitPlanner.java From cosmic with Apache License 2.0 | 5 votes |
protected Pair<List<Long>, Map<Long, Double>> listPodsByCapacity(final long zoneId, final int requiredCpu, final long requiredRam) { //look at the aggregate available cpu and ram per pod //although an aggregate value may be false indicator that a pod can host a vm, it will at the least eliminate those pods which definitely cannot //we need pods having enough cpu AND RAM to host this particular VM and order them by aggregate pod capacity if (s_logger.isDebugEnabled()) { s_logger.debug("Listing pods in order of aggregate capacity, that have (atleast one host with) enough CPU and RAM capacity under this Zone: " + zoneId); } final String capacityTypeToOrder = configDao.getValue(Config.HostCapacityTypeToOrderClusters.key()); short capacityType = Capacity.CAPACITY_TYPE_CPU; if ("RAM".equalsIgnoreCase(capacityTypeToOrder)) { capacityType = Capacity.CAPACITY_TYPE_MEMORY; } final List<Long> podIdswithEnoughCapacity = capacityDao.listPodsByHostCapacities(zoneId, requiredCpu, requiredRam, capacityType); if (s_logger.isTraceEnabled()) { s_logger.trace("PodId List having enough CPU and RAM capacity: " + podIdswithEnoughCapacity); } final Pair<List<Long>, Map<Long, Double>> result = capacityDao.orderPodsByAggregateCapacity(zoneId, capacityType); final List<Long> podIdsOrderedByAggregateCapacity = result.first(); //only keep the clusters that have enough capacity to host this VM if (s_logger.isTraceEnabled()) { s_logger.trace("PodId List in order of aggregate capacity: " + podIdsOrderedByAggregateCapacity); } podIdsOrderedByAggregateCapacity.retainAll(podIdswithEnoughCapacity); if (s_logger.isTraceEnabled()) { s_logger.trace("PodId List having enough CPU and RAM capacity & in order of aggregate capacity: " + podIdsOrderedByAggregateCapacity); } return result; }
Example 13
Source File: GccOptionsFileArgTransformer.java From pushfish-android with BSD 2-Clause "Simplified" License | 4 votes |
private List<String> getCommandLineOnlyArgs(List<String> allArgs) { List<String> commandLineOnlyArgs = new ArrayList<String>(allArgs); commandLineOnlyArgs.retainAll(CLI_ONLY_ARGS); return commandLineOnlyArgs; }
Example 14
Source File: QueryEngine.java From macrobase with Apache License 2.0 | 4 votes |
/** * Execute DIFF-JOIN query using co-optimized algorithm. NOTE: Must be a Primary Key-Foreign Key * Join. TODO: We make the following assumptions in the method below: * 1) The two joins are both inner joins over the same, single column, which is of type String * 2) The ratio metric is global_ratio * * R S T * --- --- ------------- * a a a | CA | v1 * a b b | CA | v2 * b c c | TX | v1 * b d d | TX | v2 * e e | FL | v1 * * @return result of the DIFF JOIN */ private DataFrame evaluateDiffJoin(final DataFrame outlierDf, final DataFrame inlierDf, final DataFrame common, final String joinColumn, final List<String> explainColumnNames, final double minRatioMetric) { final List<String> explainColsInCommon = Lists.newArrayList(common.getSchema().getColumnNames()); explainColsInCommon.retainAll(explainColumnNames); final int numOutliers = outlierDf.getNumRows(); final int numInliers = inlierDf.getNumRows(); log.info("Num Outliers: {}, num inliers: {}", numOutliers, numInliers); // NOTE: we assume that, because it's a PK-FK join, every value in the foreign key column // will appear in the primary key (but not vice versa). This means that evaluating the join // will never remove tuples from or add tuples to the inlier and outlier DataFrames. This allows // us to calculate the minRatioThreshold based on the total number of outliers and inliers. final double globalRatioDenom = numOutliers / (numOutliers + numInliers + 0.0); final double minRatioThreshold = minRatioMetric * globalRatioDenom; final String[] outlierProjected = outlierDf.project(joinColumn).getStringColumn(0); final String[] inlierProjected = inlierDf.project(joinColumn).getStringColumn(0); // 1) Execute \delta(\proj_{A1} R, \proj_{A1} S); final long foreignKeyDiff = System.currentTimeMillis(); final Set<String> candidateForeignKeys = foreignKeyDiff(outlierProjected, inlierProjected, minRatioThreshold); // returns K, the candidate keys that exceeded the minRatioThreshold. // K may contain false positives, though (support threshold hasn't been applied yet) log.info("Foreign key diff time: {} ms", System.currentTimeMillis() - foreignKeyDiff); log.info("Num candidate foreign keys: {}", candidateForeignKeys.size()); if (candidateForeignKeys.isEmpty()) { return new DataFrame(); } // Keep track of candidates in each column, needed for order-2 and order-3 combinations final long semiJoinAndMergeTime = System.currentTimeMillis(); // 2) Execute K \semijoin T, to get V, the values in T associated with the candidate keys, // and merge common values that distinct keys may map to final Map<String, Integer> colValuesToIndices = semiJoinAndMerge( candidateForeignKeys, // K common.getStringColumnByName(joinColumn), common.getStringColsByName(explainColsInCommon)); // T log.info("Semi-join and merge time: {} ms", System.currentTimeMillis() - semiJoinAndMergeTime); final DataFrame toReturn = diffJoinAndConcat(outlierDf, inlierDf, common, joinColumn, colValuesToIndices); return toReturn; }
Example 15
Source File: InitializationUtils.java From elasticsearch-hadoop with Apache License 2.0 | 4 votes |
public static void filterNonDataNodesIfNeeded(Settings settings, Log log) { if (!settings.getNodesDataOnly()) { return; } RestClient bootstrap = new RestClient(settings); try { String message = "No data nodes with HTTP-enabled available"; List<NodeInfo> dataNodes = bootstrap.getHttpDataNodes(); if (dataNodes.isEmpty()) { throw new EsHadoopIllegalArgumentException(message); } if (log.isDebugEnabled()) { log.debug(String.format("Found data nodes %s", dataNodes)); } List<String> toRetain = new ArrayList<String>(dataNodes.size()); for (NodeInfo node : dataNodes) { toRetain.add(node.getPublishAddress()); } List<String> ddNodes = SettingsUtils.discoveredOrDeclaredNodes(settings); // remove non-data nodes ddNodes.retainAll(toRetain); if (log.isDebugEnabled()) { log.debug(String.format("Filtered discovered only nodes %s to data-only %s", SettingsUtils.discoveredOrDeclaredNodes(settings), ddNodes)); } if (ddNodes.isEmpty()) { if (settings.getNodesDiscovery()) { message += String.format("; looks like the data nodes discovered have been removed; is the cluster in a stable state? %s", dataNodes); } else { message += String.format("; node discovery is disabled and none of nodes specified fit the criterion %s", SettingsUtils.discoveredOrDeclaredNodes(settings)); } throw new EsHadoopIllegalArgumentException(message); } SettingsUtils.setDiscoveredNodes(settings, ddNodes); } finally { bootstrap.close(); } }
Example 16
Source File: MultiChoiceEditor.java From onedev with MIT License | 4 votes |
@SuppressWarnings({"unchecked"}) @Override protected void onInitialize() { super.onInitialize(); IModel<Map<String, String>> choicesModel = new LoadableDetachableModel<Map<String, String>>() { @Override protected Map<String, String> load() { Map<String, String> choices; ComponentContext componentContext = new ComponentContext(MultiChoiceEditor.this); ComponentContext.push(componentContext); try { io.onedev.server.web.editable.annotation.ChoiceProvider choiceProvider = descriptor.getPropertyGetter().getAnnotation( io.onedev.server.web.editable.annotation.ChoiceProvider.class); Preconditions.checkNotNull(choiceProvider); Object result = ReflectionUtils.invokeStaticMethod(descriptor.getBeanClass(), choiceProvider.value()); if (result instanceof List) { choices = new LinkedHashMap<>(); for (String each: (List<String>)result) choices.put(each, each); } else { choices = (Map<String, String>)result; } } finally { ComponentContext.pop(); } return choices; } }; List<String> selections = getModelObject(); if (selections != null) selections.retainAll(choicesModel.getObject().keySet()); else selections = new ArrayList<>(); input = new StringMultiChoice("input", Model.of(selections), choicesModel) { @Override protected void onInitialize() { super.onInitialize(); getSettings().configurePlaceholder(descriptor); } }; input.setLabel(Model.of(getDescriptor().getDisplayName())); input.setRequired(descriptor.isPropertyRequired()); input.add(new AjaxFormComponentUpdatingBehavior("change"){ @Override protected void onUpdate(AjaxRequestTarget target) { onPropertyUpdating(target); } }); add(input); }
Example 17
Source File: RxList.java From RxBinding with Apache License 2.0 | 4 votes |
private boolean retainAll(List<E> list, @NonNull Collection<?> c) { final boolean result = list.retainAll(c); notifyDataSetChanged(Event.retainAll, Tuple.create(c)); return result; }
Example 18
Source File: PredictionData.java From TagRec with GNU Affero General Public License v3.0 | 4 votes |
private void determineRelevantDocs() { List<String> foundRelevantDocs = new ArrayList<String>(this.realData); foundRelevantDocs.retainAll(this.predictionData); this.numFoundRelevantDocs = foundRelevantDocs.size(); }
Example 19
Source File: FirstFitPlanner.java From cloudstack with Apache License 2.0 | 3 votes |
private void removeClustersWithoutMatchingTag(List<Long> clusterListForVmAllocation, String hostTagOnOffering) { List<Long> matchingClusters = hostDao.listClustersByHostTag(hostTagOnOffering); clusterListForVmAllocation.retainAll(matchingClusters); if (s_logger.isDebugEnabled()) { s_logger.debug("The clusterId list for the given offering tag: " + clusterListForVmAllocation); } }
Example 20
Source File: ListTest.java From java-study with Apache License 2.0 | 2 votes |
/** * 数组交集 (retainAll 会删除 ls1在ls2中没有的元素) * @param ls1 * @param ls2 * @return */ private static List<String> retainAll(List<String> ls1,List<String>ls2){ System.out.println("ls1:"+ls1+";ls2:"+ls2); ls1.retainAll(ls2); return ls1; }