Java Code Examples for java.util.HashSet#add()

The following examples show how to use java.util.HashSet#add() . 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: IteratorOperations.java    From es6draft with MIT License 6 votes vote down vote up
@Override
protected String findNext() {
    HashSet<String> visitedKeys = this.visitedKeys;
    ExecutionContext cx = this.cx;
    for (ScriptObject obj = this.obj; obj != null;) {
        for (Iterator<String> keys = this.keys; keys.hasNext();) {
            String key = keys.next();
            ScriptObject.Enumerability e = obj.isEnumerableOwnProperty(cx, key);
            if (e != ScriptObject.Enumerability.Deleted) {
                if (visitedKeys.add(key) && e == ScriptObject.Enumerability.Enumerable) {
                    return key;
                }
            }
        }
        this.obj = obj = obj.getPrototypeOf(cx);
        if (obj != null) {
            this.keys = obj.ownEnumerablePropertyKeys(cx);
        } else {
            this.keys = null;
        }
    }
    return null;
}
 
Example 2
Source File: Const.java    From hop with Apache License 2.0 6 votes vote down vote up
/**
 * Sorts the array of Strings, determines the uniquely occurring strings.
 *
 * @param strings the array that you want to do a distinct on
 * @return a sorted array of uniquely occurring strings
 */
public static String[] getDistinctStrings( String[] strings ) {
  if ( strings == null ) {
    return null;
  }
  if ( strings.length == 0 ) {
    return new String[] {};
  }
  HashSet<String> set = new HashSet<>();
  for (String string : strings) {
    set.add(string);
  }
  List<String> list = new ArrayList<>( set );
  Collections.sort(list);
  return list.toArray( new String[0] );
}
 
Example 3
Source File: EsRunner.java    From rf2-to-json-conversion with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    TransformerConfig config = new TransformerConfig();
    config.setDatabaseName("es-edition");
    config.setDefaultTermDescriptionType("900000000000003001");
    config.setDefaultTermLangCode("es");
    config.setDefaultTermLanguageRefset("900000000000509007");
    config.setEditionName("Spanish Edition");
    config.setEffectiveTime("20140430");
    config.setExpirationTime("20141231");
    config.setNormalizeTextIndex(true);
    HashSet<String> baselineFolders = new HashSet<String>();
    baselineFolders.add("/Users/alo/Downloads/Releases/SnomedCT_Release_INT_20140131/RF2Release/Snapshot");
    config.setFoldersBaselineLoad(baselineFolders);
    config.setModulesToIgnoreBaselineLoad(new ArrayList<String>());
    HashSet<String> extensionFolders = new HashSet<String>();
    extensionFolders.add("/Users/alo/Downloads/Releases/SnomedCT_Release-es_INT_20140430/RF2Release/Snapshot");
    config.setFoldersExtensionLoad(extensionFolders);
    ArrayList<String> modulesToIgnore = new ArrayList<String>();
    config.setModulesToIgnoreExtensionLoad(modulesToIgnore);

    config.setOutputFolder("/Users/alo/Downloads/Releases/es-json");

    TransformerDiskBased tr = new TransformerDiskBased();

    tr.convert(config);
}
 
Example 4
Source File: Index.java    From accumulo-examples with Apache License 2.0 6 votes vote down vote up
public static void index(int numPartitions, Text docId, String doc, String splitRegex,
    BatchWriter bw) throws Exception {

  String[] tokens = doc.split(splitRegex);

  Text partition = genPartition(doc.hashCode() % numPartitions);

  Mutation m = new Mutation(partition);

  HashSet<String> tokensSeen = new HashSet<>();

  for (String token : tokens) {
    token = token.toLowerCase();

    if (!tokensSeen.contains(token)) {
      tokensSeen.add(token);
      m.put(new Text(token), docId, new Value(new byte[0]));
    }
  }

  if (m.size() > 0)
    bw.addMutation(m);
}
 
Example 5
Source File: ApkUtils.java    From LibScout with Apache License 2.0 6 votes vote down vote up
public static Set<ZipEntry> getClassesDex(File apkFile) throws ZipException, IOException {
	HashSet<ZipEntry> result = new HashSet<ZipEntry>();
	ZipFile f = new ZipFile(apkFile);
	
    final Enumeration<? extends ZipEntry> entries = f.entries();
    while (entries.hasMoreElements()) {
        final ZipEntry entry = entries.nextElement();
        if (entry.getName().matches("classes[1-9]{0,1}\\.dex"))
        	result.add(entry);
    }
    
    // TODO: unzip those entries to tmp dir and return set<Files>

    f.close();
    return result;
}
 
Example 6
Source File: ExamGridForm.java    From unitime with Apache License 2.0 5 votes vote down vote up
public Vector<ComboBoxLookup> getEndTimes(String examType) {
    Vector<ComboBoxLookup> ret = new Vector<ComboBoxLookup>();
    HashSet added = new HashSet();
    for (Iterator i=iPeriods.get(examType).iterator();i.hasNext();) {
        ExamPeriod period = (ExamPeriod)i.next();
        if (added.add(period.getEndSlot())) {
            ret.addElement(new ComboBoxLookup(period.getEndTimeLabel(), String.valueOf(period.getEndSlot())));
        }
    }
    return ret;
}
 
Example 7
Source File: EquatableValueSet.java    From presto with Apache License 2.0 5 votes vote down vote up
static EquatableValueSet of(Type type, Object first, Object... rest)
{
    HashSet<ValueEntry> set = new LinkedHashSet<>(rest.length + 1);
    set.add(ValueEntry.create(type, first));
    for (Object value : rest) {
        set.add(ValueEntry.create(type, value));
    }
    return new EquatableValueSet(type, true, set);
}
 
Example 8
Source File: Kafka08Fetcher.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of unique topics from for the given partitions.
 *
 * @param partitions A the partitions
 * @return A list of unique topics
 */
private static List<String> getTopics(List<KafkaTopicPartitionState<TopicAndPartition>> partitions) {
	HashSet<String> uniqueTopics = new HashSet<>();
	for (KafkaTopicPartitionState<TopicAndPartition> fp: partitions) {
		uniqueTopics.add(fp.getTopic());
	}
	return new ArrayList<>(uniqueTopics);
}
 
Example 9
Source File: UidGeneratorTest.java    From moleculer-java with MIT License 5 votes vote down vote up
protected void testGenerator(UidGenerator gen) throws Exception {
	gen.started(new ServiceBroker());
	HashSet<String> set = new HashSet<>();
	for (int i = 0; i < 500; i++) {
		set.add(gen.nextUID());
	}
	assertEquals(500, set.size());
}
 
Example 10
Source File: ReflectionUtil.java    From hibersap with Apache License 2.0 5 votes vote down vote up
public static Set<Field> getHibersapSessionFields(final Object target) {
    HashSet<Field> fields = new HashSet<>();

    Field[] declaredFields = target.getClass().getDeclaredFields();
    for (Field declaredField : declaredFields) {
        if (declaredField.getAnnotation(HibersapSession.class) != null) {
            fields.add(declaredField);
        }
    }

    return fields;
}
 
Example 11
Source File: SvnLogfileParser.java    From StatSVN with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void createImplicitAction(final HashSet implicitActions, final String child, final FileBuilder childBuilder, final RevisionData parentData,
        final int k) {
    // we want to memorize this implicit action.
    final RevisionData implicit = parentData.createCopy();
    implicitActions.add(implicit);

    // avoid concurrent modification errors.
    final List toMove = new ArrayList();
    for (final Iterator it = childBuilder.getRevisions().subList(k, childBuilder.getRevisions().size()).iterator(); it.hasNext();) {
        final RevisionData revToMove = (RevisionData) it.next();
        // if
        // (!revToMove.getRevisionNumber().equals(implicit.getRevisionNumber()))
        // {
        toMove.add(revToMove);
        // }
    }

    // remove the revisions to be moved.
    childBuilder.getRevisions().removeAll(toMove);

    // don't call addRevision directly. buildRevision
    // does more.
    builder.buildFile(child, false, false, new HashMap(), new HashMap());

    // only add the implicit if the last one for the
    // file is NOT a deletion!
    // if (!toMove.isEmpty() && !((RevisionData)
    // toMove.get(0)).isDeletion()) {
    builder.buildRevision(implicit);
    // }

    // copy back the revisions we removed.
    for (final Iterator it = toMove.iterator(); it.hasNext();) {
        builder.buildRevision((RevisionData) it.next());
    }
}
 
Example 12
Source File: SearchRepoAuthorCounter.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private int count(String repoLocation) {	
	System.out.println("count ( " + repoLocation + " )");
	HashSet<String> repoAuthorsSet = new HashSet<String>();
	
	try {
		Repository repo = new FileRepository(new File(repoLocation + "/.git").getCanonicalPath());
		
		// get a list of all known heads, tags, remotes, ...
           Collection<Ref> allRefs = repo.getAllRefs().values();

           // a RevWalk allows to walk over commits based on some filtering that is defined
           try (RevWalk revWalk = new RevWalk( repo )) {
               for( Ref ref : allRefs ) {
                   revWalk.markStart( revWalk.parseCommit( ref.getObjectId() ));
               }
               System.out.println("Walking all commits starting with " + allRefs.size() + " refs: " + allRefs);
               for( RevCommit commit : revWalk ) {
               	repoAuthorsSet.add(commit.getAuthorIdent().getEmailAddress());
               }
           }
	
	} catch (IOException e) {
		System.err.println("\n" + "[" + workflow.getName() + "] " + "Failed to count repository authors. Wrong cloned repository location?");
		e.printStackTrace();
	}	 
	
	return repoAuthorsSet.size();
}
 
Example 13
Source File: FcFontConfiguration.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String[] getPlatformFontNames() {
    HashSet<String> nameSet = new HashSet<String>();
    FcFontManager fm = (FcFontManager) fontManager;
    FontConfigManager fcm = fm.getFontConfigManager();
    FcCompFont[] fcCompFonts = fcm.loadFontConfig();
    for (int i=0; i<fcCompFonts.length; i++) {
        for (int j=0; j<fcCompFonts[i].allFonts.length; j++) {
            nameSet.add(fcCompFonts[i].allFonts[j].fontFile);
        }
    }
    return nameSet.toArray(new String[0]);
}
 
Example 14
Source File: IdUtil.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
  Return an IdList with all the ids that in l1 and l2
  or null if not ids are on both lists.

  @param l1 An array of ids in normal form
  @param l2 An array of ids in nomral form
  */
public static String intersect(String[] l1, String[] l2)
{
	if (l1 == null || l2 == null) return null;
	HashSet h = new HashSet();
	for(int ix=0;ix<l2.length;ix++) h.add(l2[ix]); 
	Vector v = new Vector();
	for(int ix=0;ix<l1.length;ix++) if (h.contains(l1[ix])) v.addElement(l1[ix]);
	return vectorToIdList(v,true); 
}
 
Example 15
Source File: VarAccess.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @ast method 
 * @aspect InnerClasses
 * @declaredat /Users/eric/Documents/workspaces/clara-soot/JastAddJ/Java1.4Backend/InnerClasses.jrag:162
 */
public void collectEnclosingVariables(HashSet set, TypeDecl typeDecl) {
  Variable v = decl();
  if(!v.isInstanceVariable() && !v.isClassVariable() && v.hostType() == typeDecl)
    set.add(v);
  super.collectEnclosingVariables(set, typeDecl);
}
 
Example 16
Source File: TimeStateTest.java    From anno4j with Apache License 2.0 4 votes vote down vote up
@Test
public void testSourceDates() throws RepositoryException, IllegalAccessException, InstantiationException {
    TimeState state = this.anno4j.createObject(TimeState.class);

    TimeState result = this.anno4j.findByID(TimeState.class, state.getResourceAsString());

    assertEquals(0, result.getSourceDates().size());

    state.addSourceDate("2015-01-28T12:00:00Z");

    result = this.anno4j.findByID(TimeState.class, state.getResourceAsString());

    assertEquals(1, result.getSourceDates().size());

    HashSet<String> sourceDates = new HashSet<>();
    sourceDates.add("2015-01-28T12:00:00Z");
    sourceDates.add("2016-01-28T12:00:00Z");

    state.setSourceDates(sourceDates);

    result = this.anno4j.findByID(TimeState.class, state.getResourceAsString());

    assertEquals(2, result.getSourceDates().size());
}
 
Example 17
Source File: RemoveProvidersYMLAction.java    From walkmod-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void doAction(JsonNode node) throws Exception {
	HashSet<String> providerSet = new HashSet<String>();
	for (String elem : providers) {
		String[] partsType = elem.split(":");
		if (partsType.length == 1) {
			elem = "org.walkmod:walkmod-" + elem + "-plugin:" + elem;
		}
		if (partsType.length != 3 && partsType.length != 1) {
			throw new TransformerException("Invalid conf-provider");
		}
		providerSet.add(elem);
	}
	if (node.has("conf-providers")) {
		JsonNode aux = node.get("conf-providers");
		if (aux.isArray()) {
			ArrayNode providersList = (ArrayNode) node.get("conf-providers");
			Iterator<JsonNode> it = providersList.iterator();
			ArrayNode newProvidersList = new ArrayNode(provider.getObjectMapper().getNodeFactory());
			while (it.hasNext()) {
				JsonNode next = it.next();
				if (next.isObject()) {
					String type = next.get("type").asText();
					String[] parts = type.split(":");
					if (parts.length == 1) {
						type = "org.walkmod:walkmod-" + type + "-plugin:" + type;
					} else if (parts.length != 3) {
						throw new TransformerException("Invalid conf-provider");
					}
					if (!providerSet.contains(type)) {
						newProvidersList.add(next);
					}
				}
			}
			ObjectNode oNode = (ObjectNode) node;
			if (newProvidersList.size() > 0) {
				oNode.set("conf-providers", newProvidersList);
			} else {
				oNode.remove("conf-providers");
			}
			provider.write(node);
		}
	}

}
 
Example 18
Source File: OperationProcessorTests.java    From pravega with Apache License 2.0 4 votes vote down vote up
/**
 * Tests the ability of the OperationProcessor to process Operations when encountering invalid operations (such as
 * appends to StreamSegments that do not exist or to those that are sealed). This covers the following exceptions:
 * * StreamSegmentNotExistsException
 * * StreamSegmentSealedException
 * * General MetadataUpdateException.
 */
@Test
public void testWithInvalidOperations() throws Exception {
    int streamSegmentCount = 10;
    int appendsPerStreamSegment = 40;
    long sealedStreamSegmentId = 6; // We are going to prematurely seal this StreamSegment.
    long deletedStreamSegmentId = 8; // We are going to prematurely mark this StreamSegment as deleted.
    long nonExistentStreamSegmentId; // This is a bogus StreamSegment, that does not exist.

    @Cleanup
    TestContext context = new TestContext();

    // Generate some test data (no need to complicate ourselves with Transactions here; that is tested in the no-failure test).
    HashSet<Long> streamSegmentIds = createStreamSegmentsInMetadata(streamSegmentCount, context.metadata);
    nonExistentStreamSegmentId = streamSegmentIds.size();
    streamSegmentIds.add(nonExistentStreamSegmentId);
    context.metadata.getStreamSegmentMetadata(sealedStreamSegmentId).markSealed();
    context.metadata.getStreamSegmentMetadata(deletedStreamSegmentId).markDeleted();
    List<Operation> operations = generateOperations(streamSegmentIds, new HashMap<>(), appendsPerStreamSegment,
            METADATA_CHECKPOINT_EVERY, false, false);

    // Setup an OperationProcessor and start it.
    @Cleanup
    TestDurableDataLog dataLog = TestDurableDataLog.create(CONTAINER_ID, MAX_DATA_LOG_APPEND_SIZE, executorService());
    dataLog.initialize(TIMEOUT);
    @Cleanup
    OperationProcessor operationProcessor = new OperationProcessor(context.metadata, context.stateUpdater,
            dataLog, getNoOpCheckpointPolicy(), executorService());
    operationProcessor.startAsync().awaitRunning();

    // Process all generated operations.
    List<OperationWithCompletion> completionFutures = processOperations(operations, operationProcessor);

    // Wait for all such operations to complete. We are expecting exceptions, so verify that we do.
    AssertExtensions.assertThrows(
            "No operations failed.",
            OperationWithCompletion.allOf(completionFutures)::join,
            ex -> ex instanceof MetadataUpdateException || ex instanceof StreamSegmentException);

    HashSet<Long> streamSegmentsWithNoContents = new HashSet<>();
    streamSegmentsWithNoContents.add(sealedStreamSegmentId);
    streamSegmentsWithNoContents.add(deletedStreamSegmentId);
    streamSegmentsWithNoContents.add(nonExistentStreamSegmentId);

    // Verify that the "right" operations failed, while the others succeeded.
    for (OperationWithCompletion oc : completionFutures) {
        if (oc.operation instanceof StorageOperation) {
            long streamSegmentId = ((StorageOperation) oc.operation).getStreamSegmentId();
            if (streamSegmentsWithNoContents.contains(streamSegmentId)) {
                Assert.assertTrue("Completion future for invalid StreamSegment " + streamSegmentId + " did not complete exceptionally.",
                        oc.completion.isCompletedExceptionally());
                Predicate<Throwable> errorValidator;
                if (streamSegmentId == sealedStreamSegmentId) {
                    errorValidator = ex -> ex instanceof StreamSegmentSealedException;
                } else if (streamSegmentId == deletedStreamSegmentId) {
                    errorValidator = ex -> ex instanceof StreamSegmentNotExistsException;
                } else {
                    errorValidator = ex -> ex instanceof MetadataUpdateException;
                }

                AssertExtensions.assertThrows("Unexpected exception for failed Operation.", oc.completion::join, errorValidator);
                continue;
            }
        }

        // If we get here, we must verify no exception was thrown.
        oc.completion.join();
    }

    performLogOperationChecks(completionFutures, context.memoryLog, dataLog, context.metadata);
    performMetadataChecks(streamSegmentIds, streamSegmentsWithNoContents, new HashMap<>(), completionFutures, context.metadata, false, false);
    performReadIndexChecks(completionFutures, context.readIndex);
    operationProcessor.stopAsync().awaitTerminated();
}
 
Example 19
Source File: Test.java    From EasyEE with MIT License 4 votes vote down vote up
@SuppressWarnings("unused")
	public static void main(String[] args) {

		String str="#AAAA#BBBB#CCCC#DDDD#EEEE#FFFF#GGGG#HHHH#IIII#JJJJ#KKKK#LLLL#MMMM#NNNN#";
		
		HashSet<String> set=new HashSet<String>();
		set.add("AAAA");
		set.add("BBBB");
		set.add("CCCC");
		set.add("DDDD");
		set.add("EEEE");
		set.add("FFFF");
		set.add("GGGG");
		set.add("HHHH");
		set.add("IIII");
		set.add("JJJJ");
		set.add("KKKK");
		set.add("LLLL");
		set.add("MMMM");
		set.add("NNNN");
		
		long s=System.currentTimeMillis();
		for(int i=0;i<=100000;i++){
//			str.indexOf("NNNN");
			"".trim().equals("");
		}
		long e=System.currentTimeMillis();
		
		long s2=System.currentTimeMillis();
		for(int i=0;i<=100000;i++){
//			set.contains("NNNN");
			boolean f="fsffsaaaaaaaa".trim().length()>0;
		}
		long e2=System.currentTimeMillis();
		
		System.out.println("str:"+(e-s)+"ms");
		System.out.println("set:"+(e2-s2)+"ms");
		
		
		System.out.println(Arrays.toString("a,b,c".split(",")));
		System.out.println(Arrays.toString("a,b,c,".split(",")));
		System.out.println(Arrays.toString(",a,b,c,".split(",")));
		System.out.println(Arrays.toString(",a,b,c,".split("")));
		System.out.println(Arrays.toString(",a#b,c,".split(",|#")));
		System.out.println(Arrays.toString("fasfsa/a.fd".split(",|#")));
	
	}
 
Example 20
Source File: StackVarsProcessor.java    From JByteMod-Beta with GNU General Public License v2.0 4 votes vote down vote up
private static boolean isVersionToBeReplaced(VarVersionPair usedvar, HashMap<Integer, HashSet<VarVersionPair>> mapVars,
    SSAUConstructorSparseEx ssau, VarVersionPair leftpaar) {

  VarVersionsGraph ssuversions = ssau.getSsuversions();

  SFormsFastMapDirect mapLiveVars = ssau.getLiveVarVersionsMap(usedvar);
  if (mapLiveVars == null) {
    // dummy version, predecessor of a phi node
    return false;
  }

  // compare protected ranges
  if (!InterpreterUtil.equalObjects(ssau.getMapVersionFirstRange().get(leftpaar), ssau.getMapVersionFirstRange().get(usedvar))) {
    return false;
  }

  for (Entry<Integer, HashSet<VarVersionPair>> ent : mapVars.entrySet()) {
    FastSparseSet<Integer> liveverset = mapLiveVars.get(ent.getKey());
    if (liveverset == null) {
      return false;
    }

    HashSet<VarVersionNode> domset = new HashSet<>();
    for (VarVersionPair verpaar : ent.getValue()) {
      domset.add(ssuversions.nodes.getWithKey(verpaar));
    }

    boolean isdom = false;

    for (Integer livever : liveverset) {
      VarVersionNode node = ssuversions.nodes.getWithKey(new VarVersionPair(ent.getKey().intValue(), livever.intValue()));

      if (ssuversions.isDominatorSet(node, domset)) {
        isdom = true;
        break;
      }
    }

    if (!isdom) {
      return false;
    }
  }

  return true;
}