Java源码示例:java.util.HashSet
示例1
@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
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
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
/** {@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
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
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
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
/**
* <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
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;
}
示例10
/**
* {@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
/**
* 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
@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
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
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
/**
* 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;
}
示例16
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
@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
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
/**
* @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
@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);
}
示例21
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
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
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;
}
示例24
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
@Override
public Set<String> requiredParameters() {
final Set<String> req = new HashSet<>();
req.add("value");
req.add("attribute");
return req;
}
示例26
@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
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
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
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
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;
}