类java.util.HashSet源码实例Demo

下面列出了怎么用java.util.HashSet的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: RxUploader   文件: SimpleUploadDataStoreTest.java
@SuppressLint("ApplySharedPref")
@Test
public void testGetInvalidJobId() throws Exception {
    final Job test = createTestJob();
    final String json = gson.toJson(test);
    final String key = SimpleUploadDataStore.jobIdKey(test.id());
    final Set<String> keys = new HashSet<>();
    keys.add(key);

    final SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putStringSet(SimpleUploadDataStore.KEY_JOB_IDS, keys);
    editor.putString(key, json);
    editor.commit();

    final TestSubscriber<Job> ts = TestSubscriber.create();
    dataStore.get("bad_id").subscribe(ts);

    ts.awaitTerminalEvent(1, TimeUnit.SECONDS);
    ts.assertNoErrors();
    ts.assertValueCount(1);
    ts.assertValue(Job.INVALID_JOB);
}
 
源代码2 项目: DNC   文件: ArrivalBoundDispatch.java
private static Set<ArrivalCurve> getPermutations(Set<ArrivalCurve> arrival_curves_1,
		Set<ArrivalCurve> arrival_curves_2) {
	if (arrival_curves_1.isEmpty()) {
		return new HashSet<ArrivalCurve>(arrival_curves_2);
	}
	if (arrival_curves_2.isEmpty()) {
		return new HashSet<ArrivalCurve>(arrival_curves_1);
	}

	Set<ArrivalCurve> arrival_bounds_merged = new HashSet<ArrivalCurve>();

	for (ArrivalCurve alpha_1 : arrival_curves_1) {
		for (ArrivalCurve alpha_2 : arrival_curves_2) {
			arrival_bounds_merged.add(Curve.getUtils().add(alpha_1, alpha_2));
		}
	}

	return arrival_bounds_merged;
}
 
源代码3 项目: securify   文件: JumpI.java
private Set<Instruction> getAllReachableInstructions(Instruction start) {
	Set<Instruction> reachable = new HashSet<>();
	reachable.add(start);
	Queue<Instruction> bfs = new LinkedList<>();
	bfs.add(start);
	while (!bfs.isEmpty()) {
		Instruction i = bfs.poll();
		// add next instruction
		Instruction next = i.getNext();
		if (next != null && !reachable.contains(next)) {
			reachable.add(next);
			bfs.add(next);
		}
		// check for additional jump destinations
		if (i instanceof BranchInstruction && !(i instanceof _VirtualInstruction)) {
			((BranchInstruction)i).getOutgoingBranches().forEach(jdest -> {
				if (!reachable.contains(jdest)) {
					reachable.add(jdest);
					bfs.add(jdest);
				}
			});
		}
	}
	return reachable;
}
 
源代码4 项目: steady   文件: PythonArchiveAnalyzer.java
/** {@inheritDoc} */
@Override
public Set<FileAnalyzer> getChilds(boolean _recursive) {
	final Set<FileAnalyzer> nested_fa = new HashSet<FileAnalyzer>();
	if(!_recursive) {
		nested_fa.addAll(this.nestedAnalyzers);
	}
	else {
		for(FileAnalyzer fa: this.nestedAnalyzers) {
			nested_fa.add(fa);
			final Set<FileAnalyzer> nfas = fa.getChilds(true);
			if(nfas!=null && !nfas.isEmpty())
				nested_fa.addAll(nfas);
		}
	}
	return nested_fa;
}
 
源代码5 项目: netbeans   文件: GeneralKnockout.java
protected void checkCompletionDoesntContainHtmlItems(CompletionJListOperator jlist, String[] invalidList) {
    try {
        List items = jlist.getCompletionItems();
        HashSet<String> completion = new HashSet<>();
        for (Object item : items) {
            if (item instanceof HtmlCompletionItem) {
                completion.add(((HtmlCompletionItem) item).getItemText());
            } else {
                completion.add(item.toString());
            }
        }
            for (String sCode : invalidList) {
            if (completion.contains(sCode)) {
                fail("Completion list contains invalid item:" + sCode);
            }
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
源代码6 项目: onos   文件: NodeSelection.java
private Set<String> findHosts(Set<String> ids) {
    Set<String> unmatched = new HashSet<>();
    Host host;

    for (String id : ids) {
        try {
            host = hostService.getHost(hostId(id));
            if (host != null) {
                hosts.add(host);
            } else {
                unmatched.add(id);
            }
        } catch (Exception e) {
            unmatched.add(id);
        }
    }
    return unmatched;
}
 
源代码7 项目: incubator-retired-blur   文件: CsvBlurDriver.java
private static Set<Path> recurisvelyGetPathesContainingFiles(Path path, Configuration configuration)
    throws IOException {
  Set<Path> pathSet = new HashSet<Path>();
  FileSystem fileSystem = path.getFileSystem(configuration);
  if (!fileSystem.exists(path)) {
    LOG.warn("Path not found [{0}]", path);
    return pathSet;
  }
  FileStatus[] listStatus = fileSystem.listStatus(path);
  for (FileStatus status : listStatus) {
    if (status.isDir()) {
      pathSet.addAll(recurisvelyGetPathesContainingFiles(status.getPath(), configuration));
    } else {
      pathSet.add(status.getPath().getParent());
    }
  }
  return pathSet;
}
 
源代码8 项目: steady   文件: PathSimilarity.java
/**
 * <p>groupPathsByJointNode.</p>
 */
public void groupPathsByJointNode () {
	this.groupedPaths = new HashMap<String, HashSet<Integer>>();
	for (int i = 0; i < this.paths.size(); i++) {
		LinkedList<String> p = this.paths.get(i);
		for(String s : p) {
			if(!this.groupedPaths.containsKey(s)) {
				HashSet<Integer> tmp = new HashSet<Integer>();
				tmp.add(i);
				this.groupedPaths.put(s, tmp);
			} else {
				this.groupedPaths.get(s).add(i);
			}
		}
	}
}
 
源代码9 项目: jdk8u-dev-jdk   文件: ConditionalSpecialCasing.java
private static char[] lookUpTable(String src, int index, Locale locale, boolean bLowerCasing) {
    HashSet<Entry> set = entryTable.get(new Integer(src.codePointAt(index)));
    char[] ret = null;

    if (set != null) {
        Iterator<Entry> iter = set.iterator();
        String currentLang = locale.getLanguage();
        while (iter.hasNext()) {
            Entry entry = iter.next();
            String conditionLang = entry.getLanguage();
            if (((conditionLang == null) || (conditionLang.equals(currentLang))) &&
                    isConditionMet(src, index, locale, entry.getCondition())) {
                ret = bLowerCasing ? entry.getLowerCase() : entry.getUpperCase();
                if (conditionLang != null) {
                    break;
                }
            }
        }
    }

    return ret;
}
 
/**
 * {@inheritDoc}
 */
@Override
protected void buttonPressed(final int buttonId) {
	if (buttonId == IDialogConstants.OK_ID) {
		fData.setRefactoringAware(true);
		final RefactoringDescriptorProxy[] descriptors= fHistoryControl.getCheckedDescriptors();
		Set<IProject> set= new HashSet<IProject>();
		IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
		for (int index= 0; index < descriptors.length; index++) {
			final String project= descriptors[index].getProject();
			if (project != null && !"".equals(project)) //$NON-NLS-1$
				set.add(root.getProject(project));
		}
		fData.setRefactoringProjects(set.toArray(new IProject[set.size()]));
		fData.setRefactoringDescriptors(descriptors);
		fData.setExportStructuralOnly(fExportStructural.getSelection());
		final IDialogSettings settings= fSettings;
		if (settings != null)
			settings.put(SETTING_SORT, fHistoryControl.isSortByProjects());
	}
	super.buttonPressed(buttonId);
}
 
源代码11 项目: BotLibre   文件: SelfDecompiler.java
/**
 * Print the formula to create a unique instance of it.
 */
public Vertex createUniqueTemplate(Vertex formula, Network network) {
	try {
		StringWriter writer = new StringWriter();
		printTemplate(formula, writer, "", new ArrayList<Vertex>(), new ArrayList<Vertex>(), new HashSet<Vertex>(), network);
		String source = writer.toString();
		if (source.length() > AbstractNetwork.MAX_TEXT) {
			return formula;
		}
		// Maintain identity on formulas through printing them.
		Vertex existingFormula = network.createVertex(source);
		if (!existingFormula.instanceOf(Primitive.FORMULA)) {
			for (Iterator<Relationship> iterator = formula.orderedAllRelationships(); iterator.hasNext(); ) {
				Relationship relationship = iterator.next();
				existingFormula.addRelationship(relationship.getType(), relationship.getTarget(), relationship.getIndex());
			}
		}
		return existingFormula;
	} catch (IOException ignore) {
		throw new BotException(ignore);
	}
}
 
源代码12 项目: JGiven   文件: ProxyClassPerformanceTest.java
@Test
public void test_creation_of_proxy_classes(){
    Set<Long> results = new HashSet<>();
    for( int i = 0; i < 1000; i++ ) {
        ScenarioBase scenario = new ScenarioBase();
        TestStage testStage = scenario.addStage( TestStage.class );
        testStage.something();
        if( i % 100 == 0 ) {
            System.gc();
            long usedMemory = ( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() ) / ( 1024 * 1024 );
            System.out.println( "Used memory: " + usedMemory );
            results.add( usedMemory );
        }
    }

    assertThat( results )
            .describedAs( "Only should contains 1 or 2 items, as first iteration might use more memory might contain 2 items" )
            .hasSizeBetween( 1, 2 );
}
 
源代码13 项目: ant-ivy   文件: SearchEngine.java
public String[] listModules(String org) {
    Set<String> entries = new HashSet<>();

    Map<String, Object> tokenValues = new HashMap<>();
    tokenValues.put(IvyPatternHelper.ORGANISATION_KEY, org);

    for (DependencyResolver resolver : settings.getResolvers()) {
        Map<String, String>[] modules = resolver.listTokenValues(
            new String[] {IvyPatternHelper.MODULE_KEY}, tokenValues);
        for (Map<String, String> module : modules) {
            entries.add(module.get(IvyPatternHelper.MODULE_KEY));
        }
    }

    return entries.toArray(new String[entries.size()]);
}
 
源代码14 项目: nakadi   文件: EventTypeChangeListener.java
private void onEventTypeInvalidated(final String eventType) {
    final Optional<Set<InternalListener>> toNotify;
    readWriteLock.readLock().lock();
    try {
        toNotify = Optional.ofNullable(eventTypeToListeners.get(eventType))
                .map(HashSet<InternalListener>::new);
    } finally {
        readWriteLock.readLock().unlock();
    }
    if (toNotify.isPresent()) {
        for (final InternalListener listener : toNotify.get()) {
            try {
                listener.authorizationChangeListener.accept(eventType);
            } catch (RuntimeException ex) {
                LOG.error("Failed to notify listener " + listener, ex);
            }
        }
    }
}
 
源代码15 项目: TencentKona-8   文件: Utils.java
/**
 * A small implementation of UNIX find.
 * @param matchRegex Only collect paths that match this regex.
 * @param pruneRegex Don't recurse down a path that matches this regex. May be null.
 * @throws IOException if File.getCanonicalPath() fails.
 */
public static List<File> find(final File startpath, final String matchRegex, final String pruneRegex) throws IOException{
    final Pattern matchPattern = Pattern.compile(matchRegex, Pattern.CASE_INSENSITIVE);
    final Pattern prunePattern = pruneRegex == null ? null : Pattern.compile(pruneRegex, Pattern.CASE_INSENSITIVE);
    final Set<String> visited = new HashSet<String>();
    final List<File> found = new ArrayList<File>();
    class Search{
        void search(final File path) throws IOException{
            if(prunePattern != null && prunePattern.matcher(path.getAbsolutePath()).matches()) return;
            String cpath = path.getCanonicalPath();
            if(!visited.add(cpath))  return;
            if(matchPattern.matcher(path.getAbsolutePath()).matches())
                found.add(path);
            if(path.isDirectory())
                for(File sub : path.listFiles())
                    search(sub);
        }
    }
    new Search().search(startpath);
    return found;
}
 
private void recalculateCheckedState(List<IWorkingSet> addedWorkingSets) {
	Set<IWorkingSet> checkedWorkingSets= new HashSet<IWorkingSet>();
	GrayedCheckedModelElement[] elements= fModel.getChecked();
	for (int i= 0; i < elements.length; i++)
		checkedWorkingSets.add(elements[i].getWorkingSet());

	if (addedWorkingSets != null)
		checkedWorkingSets.addAll(addedWorkingSets);

	fModel= createGrayedCheckedModel(fElements, getAllWorkingSets(), checkedWorkingSets);

	fTableViewer.setInput(fModel);
	fTableViewer.refresh();
	fTableViewer.setCheckedElements(fModel.getChecked());
	fTableViewer.setGrayedElements(fModel.getGrayed());
}
 
源代码17 项目: RemotePreferences   文件: RemotePreferencesTest.java
@Test
public void testStringSetRead() {
    HashSet<String> set = new HashSet<>();
    set.add("Chocola");
    set.add("Vanilla");
    set.add("Coconut");
    set.add("Azuki");
    set.add("Maple");
    set.add("Cinnamon");

    getSharedPreferences()
        .edit()
        .putStringSet("pref", set)
        .apply();

    RemotePreferences remotePrefs = getRemotePreferences(true);
    Assert.assertEquals(set, remotePrefs.getStringSet("pref", null));
}
 
源代码18 项目: kylin   文件: DataModelDesc.java
private boolean validate() {

        // ensure no dup between dimensions/metrics
        for (ModelDimensionDesc dim : dimensions) {
            String table = dim.getTable();
            for (String c : dim.getColumns()) {
                TblColRef dcol = findColumn(table, c);
                metrics = ArrayUtils.removeElement(metrics, dcol.getIdentity());
            }
        }

        Set<TblColRef> mcols = new HashSet<>();
        for (String m : metrics) {
            mcols.add(findColumn(m));
        }

        // validate PK/FK are in dimensions
        boolean pkfkDimAmended = false;
        for (Chain chain : joinsTree.getTableChains().values()) {
            pkfkDimAmended = validatePkFkDim(chain.join, mcols) || pkfkDimAmended;
        }
        return pkfkDimAmended;
    }
 
源代码19 项目: sakai   文件: SitePermsService.java
/**
 * @return a list of all valid roles names
 */
public List<String> getValidRoles() {
    HashSet<String> roleIds = new HashSet<String>();
    for (String templateRef : getTemplateRoles()) {
        AuthzGroup ag;
        try {
            ag = authzGroupService.getAuthzGroup(templateRef);
            Set<Role> agRoles = ag.getRoles();
            for (Role role : agRoles) {
                roleIds.add(role.getId());
            }
        } catch (GroupNotDefinedException e) {
            // nothing to do here but continue really
        }
    }
    ArrayList<String> roles = new ArrayList<String>(roleIds);
    Collections.sort(roles);
    return roles;
}
 
源代码20 项目: component-runtime   文件: ProjectResourceTest.java
@Test
void configuration(final WebTarget target) {
    final FactoryConfiguration config = target
            .path("project/configuration")
            .request(MediaType.APPLICATION_JSON_TYPE)
            .get(FactoryConfiguration.class);
    final String debug = config.toString();
    assertEquals(new HashSet<>(asList("Gradle", "Maven")), new HashSet<>(config.getBuildTypes()), debug);
    assertEquals(new HashMap<String, List<FactoryConfiguration.Facet>>() {

        {
            put("Test", singletonList(new FactoryConfiguration.Facet("Talend Component Kit Testing",
                    "Generates test(s) for each component.")));
            put("Runtime", singletonList(new FactoryConfiguration.Facet("Apache Beam",
                    "Generates some tests using beam runtime instead of Talend Component Kit Testing framework.")));
            put("Libraries", singletonList(new FactoryConfiguration.Facet("WADL Client Generation",
                    "Generates a HTTP client from a WADL.")));
            put("Tool",
                    asList(new FactoryConfiguration.Facet("Codenvy",
                            "Pre-configures the project to be usable with Codenvy."),
                            new FactoryConfiguration.Facet("Travis CI",
                                    "Creates a .travis.yml pre-configured for a component build.")));
        }
    }, new HashMap<>(config.getFacets()), debug);
}
 
static Set<String> getAssignedTrackedEntityAttributeUids(List<Program> programs, List<TrackedEntityType> types) {
    Set<String> attributeUids = new HashSet<>();

    for (Program program : programs) {
        List<ProgramTrackedEntityAttribute> attributes =
                ProgramInternalAccessor.accessProgramTrackedEntityAttributes(program);
        if (attributes != null) {
            for (ProgramTrackedEntityAttribute programAttribute : attributes) {
                attributeUids.add(programAttribute.trackedEntityAttribute().uid());
            }
        }
    }

    for (TrackedEntityType type : types) {
        if (type.trackedEntityTypeAttributes() != null) {
            for (TrackedEntityTypeAttribute attribute : type.trackedEntityTypeAttributes()) {
                attributeUids.add(attribute.trackedEntityAttribute().uid());
            }
        }
    }

    return attributeUids;
}
 
源代码22 项目: smallrye-graphql   文件: Bootstrap.java
private GraphQLSchema generateGraphQLSchema() {
    GraphQLSchema.Builder schemaBuilder = GraphQLSchema.newSchema();

    createGraphQLEnumTypes();
    createGraphQLInterfaceTypes();
    createGraphQLObjectTypes();
    createGraphQLInputObjectTypes();

    addQueries(schemaBuilder);
    addMutations(schemaBuilder);

    schemaBuilder.additionalTypes(new HashSet<>(enumMap.values()));
    schemaBuilder.additionalTypes(new HashSet<>(interfaceMap.values()));
    schemaBuilder.additionalTypes(new HashSet<>(typeMap.values()));
    schemaBuilder.additionalTypes(new HashSet<>(inputMap.values()));

    codeRegistryBuilder.fieldVisibility(getGraphqlFieldVisibility());
    schemaBuilder = schemaBuilder.codeRegistry(codeRegistryBuilder.build());

    // register error info
    ErrorInfoMap.register(schema.getErrors());

    return schemaBuilder.build();
}
 
源代码23 项目: core   文件: PropTest.java
public static Set<String> getKeys(File f) throws Exception {
    Set<String> keys = new HashSet<>();

    try(BufferedReader br = new BufferedReader(new FileReader(f))) {
        for(String line; (line = br.readLine()) != null; ) {
            if(!line.equals("") && !line.startsWith("#"))
                keys.add(line.split("=")[0]);
        }
    }

    return keys;
}
 
public Component getComponentBefore(Container focusCycleRoot,
                                    Component aComponent) {
    Component hardCoded = aComponent, prevHardCoded;
    HashSet<Component> sanity = new HashSet<Component>();

    do {
        prevHardCoded = hardCoded;
        hardCoded = backwardMap.get(hardCoded);
        if (hardCoded == null) {
            if (delegatePolicy != null &&
                prevHardCoded.isFocusCycleRoot(focusCycleRoot)) {
                return delegatePolicy.getComponentBefore(focusCycleRoot,
                                                   prevHardCoded);
            } else if (delegateManager != null) {
                return delegateManager.
                    getComponentBefore(focusCycleRoot, aComponent);
            } else {
                return null;
            }
        }
        if (sanity.contains(hardCoded)) {
            // cycle detected; bail
            return null;
        }
        sanity.add(hardCoded);
    } while (!accept(hardCoded));

    return hardCoded;
}
 
源代码25 项目: lams   文件: SetAttributeHandler.java
@Override
public Set<String> requiredParameters() {
    final Set<String> req = new HashSet<>();
    req.add("value");
    req.add("attribute");
    return req;
}
 
源代码26 项目: codebase   文件: ProcessModel.java
@SuppressWarnings("unchecked")
	@Override
	public Collection<FlowNode> getOutputFlowNodes(NonFlowNode obj) {
		Set<FlowNode> result = new HashSet<FlowNode>();
		//given node part of this graph?
		//31.07.2012 Temporary Remove
		//		if (this.nonFlowNodes.contains(obj)){
//			if (obj instanceof IDataNode){
//				result.addAll((Collection<? extends FlowNode>) ((IDataNode) obj).getReadingFlowNodes());
//				result.addAll((Collection<? extends FlowNode>) ((IDataNode) obj).getUnspecifiedFlowNodes());
//			}
//		}
		return result;
	}
 
源代码27 项目: hugegraph-studio   文件: StudioApiConfig.java
public Set<String> getAppendLimitSuffixes() {
    List<String> gremlins =
            this.config.get(StudioApiOptions.GREMLINS_APPEND_LIMIT_SUFFIX);

    if (gremlins == null || gremlins.size() == 0) {
        return new HashSet<>();
    }
    Set<String> gremlinSet = new HashSet<>(gremlins);
    for (String g : gremlins) {
        gremlinSet.add(g);
    }
    return gremlinSet;
}
 
源代码28 项目: jolie   文件: SchemaDocumentImpl.java
public Set<SchemaDocument> getImportedDocuments(String targetNamespace) {
    if(targetNamespace==null)
        throw new IllegalArgumentException();
    Set<SchemaDocument> r = new HashSet<SchemaDocument>();
    for (SchemaDocumentImpl doc : references) {
        if(doc.getTargetNamespace().equals(targetNamespace))
            r.add(doc);
    }
    return Collections.unmodifiableSet(r);
}
 
源代码29 项目: ipst   文件: UniqueTopologyChecker.java
private static Set<Set<String>> toTopoSet(PossibleTopology.Substation ps, ShortIdDictionary dict) {
    Set<Set<String>> sets = new HashSet<>();
    for (PossibleTopology.Bus b : ps.getBuses()) {
        if (isBusValid(b)) {
            Set<String> set = new HashSet<>();
            for (PossibleTopology.Equipment eq : b.getEquipments()) {
                set.add(dict != null ? dict.getShortId(eq.getId()) : eq.getId());
            }
            sets.add(set);
        }
    }
    return sets;
}
 
源代码30 项目: tracecompass   文件: StateSystemDataProvider.java
private static Set<Long> getTimes(ITmfStateSystem key, @Nullable List<Long> timeRequested) {
    if (timeRequested == null) {
        return Collections.emptySet();
    }
    Set<@NonNull Long> times = new HashSet<>();
    for (long t : timeRequested) {
        if (key.getStartTime() <= t && t <= key.getCurrentEndTime()) {
            times.add(t);
        }
    }
    return times;
}
 
 类所在包
 同包方法