下面列出了java.util.LinkedHashSet#iterator ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void main(String[] args) {
//create object of LinkedHashSet
LinkedHashSet lhashSet = new LinkedHashSet();
//add elements to LinkedHashSet object
lhashSet.add(new Integer("1"));
lhashSet.add(new Integer("2"));
lhashSet.add(new Integer("3"));
//get the Iterator
Iterator itr = lhashSet.iterator();
System.out.println("LinkedHashSet contains : ");
while (itr.hasNext()) System.out.println(itr.next());
}
/**
* Get back a Map of String*String from its String representation.
* Unescape backslashed separator characters.
* @param string String to convert to a Map
* @return a Map
* @see #toString(java.util.Map)
*/
public static Map<String, String> toMap(String string) {
Map<String, String> map = new HashMap<String, String>();
if (string == null
|| string.length() < 3) {
return map;
}
Set<String> firstList = toSet(string, ", ");
for (String element : firstList) {
LinkedHashSet<String> secondList = toSet("[" + element + "]", "=");
if (secondList.size() == 2) {
Iterator<String> iterator = secondList.iterator();
map.put(iterator.next(), iterator.next());
} else {
Err.prln("Ignoring element: [" + element + "]");
Err.prln("Expecting: [key=value]");
}
}
return map;
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
final LinkedHashSet<URL> resourceUrls = new LinkedHashSet<URL>();
final Iterator<ClassLoader> clIterator = newClassLoaderIterator();
while ( clIterator.hasNext() ) {
final ClassLoader classLoader = clIterator.next();
final Enumeration<URL> urls = classLoader.getResources( name );
while ( urls.hasMoreElements() ) {
resourceUrls.add( urls.nextElement() );
}
}
return new Enumeration<URL>() {
final Iterator<URL> resourceUrlIterator = resourceUrls.iterator();
@Override
public boolean hasMoreElements() {
return resourceUrlIterator.hasNext();
}
@Override
public URL nextElement() {
return resourceUrlIterator.next();
}
};
}
public static void main(String[] args) {
//create object of LinkedHashSet
LinkedHashSet lhashSet = new LinkedHashSet();
//add elements to LinkedHashSet object
lhashSet.add(new Integer("1"));
lhashSet.add(new Integer("2"));
lhashSet.add(new Integer("3"));
//get the Iterator
Iterator itr = lhashSet.iterator();
System.out.println("LinkedHashSet contains : ");
while (itr.hasNext()) System.out.println(itr.next());
}
@Override
public Iterator<AbstractFeature> getFois(final IFoiFilter filter)
{
// use producer list from filter or use all producers
Collection<String> producerIDs = filter.getProducerIDs();
if (producerIDs == null || producerIDs.isEmpty())
producerIDs = this.getProducerIDs();
// we're forced to temporarily hold the whole set in memory to remove duplicates
LinkedHashSet<AbstractFeature> fois = new LinkedHashSet<AbstractFeature>();
for (String producerID: producerIDs)
{
Iterator<AbstractFeature> it = getEntityStorage(producerID).getFois(filter);
while (it.hasNext())
fois.add(it.next());
}
return fois.iterator();
}
@Override
public Iterator<String> getFoiIDs(final IFoiFilter filter)
{
// use producer list from filter or use all producers
Collection<String> producerIDs = filter.getProducerIDs();
if (producerIDs == null || producerIDs.isEmpty())
producerIDs = this.getProducerIDs();
// we're forced to temporarily hold the whole set in memory to remove duplicates
LinkedHashSet<String> foiIDs = new LinkedHashSet<String>();
for (String producerID: producerIDs)
{
Iterator<String> it = getEntityStorage(producerID).getFoiIDs(filter);
while (it.hasNext())
foiIDs.add(it.next());
}
return foiIDs.iterator();
}
/**
* @param oldTeam
* @return
*/
private Team fillBindingsForTeam(Team oldTeam) {
TeamImpl newTeam = new TeamImpl(oldTeam);
List<String> namesList = newTeam.getNames();
for (String name : namesList) {
LinkedHashSet<Character> prefs = getAllAvailableBindingsFor(name, newTeam);
Iterator<Character> itr = prefs.iterator();
while (newTeam.getBinding(name) == null && itr.hasNext()) {
newTeam.setBinding(name, itr.next());
}
if (newTeam.getBinding(name) == null) {
LOG.severe("Cannot find an appropriate binding for a species: " + String.valueOf(name));
}
}
return newTeam;
}
private static LookupElement[] initLookupItems(LinkedHashSet<String> names,
PsiNamedElement elementToRename,
PsiElement nameSuggestionContext,
final boolean shouldSelectAll) {
if (names == null) {
names = new LinkedHashSet<String>();
for (NameSuggestionProvider provider : Extensions.getExtensions(NameSuggestionProvider.EP_NAME)) {
final SuggestedNameInfo suggestedNameInfo = provider.getSuggestedNames(elementToRename, nameSuggestionContext, names);
if (suggestedNameInfo != null &&
provider instanceof PreferrableNameSuggestionProvider &&
!((PreferrableNameSuggestionProvider)provider).shouldCheckOthers()) {
break;
}
}
}
final LookupElement[] lookupElements = new LookupElement[names.size()];
final Iterator<String> iterator = names.iterator();
for (int i = 0; i < lookupElements.length; i++) {
final String suggestion = iterator.next();
lookupElements[i] = LookupElementBuilder.create(suggestion).withInsertHandler(new InsertHandler<LookupElement>() {
@Override
public void handleInsert(InsertionContext context, LookupElement item) {
if (shouldSelectAll) return;
final Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(context.getEditor());
final TemplateState templateState = TemplateManagerImpl.getTemplateState(topLevelEditor);
if (templateState != null) {
final TextRange range = templateState.getCurrentVariableRange();
if (range != null) {
topLevelEditor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), suggestion);
}
}
}
});
}
return lookupElements;
}
/** Collects all (transitive) dependencies of the given project */
private void collectProjectDependencies(Path projectDir, Map<Path, ProjectDescription> pdCache,
LinkedHashSet<Path> dependencies) {
NodeModulesFolder nodeModulesFolder = nodeModulesDiscoveryHelper.getNodeModulesFolder(projectDir, pdCache);
LinkedHashSet<Path> workList = new LinkedHashSet<>();
workList.add(projectDir);
while (!workList.isEmpty()) {
Iterator<Path> iterator = workList.iterator();
Path nextProject = iterator.next();
iterator.remove();
findDependencies(nextProject, nodeModulesFolder, pdCache, workList, dependencies);
}
}
/**
* 获取linkedHashSet中元素的索引位置
*
* @param linkedHashSet
* @param string
* @return
*/
public static int getIndexInLinkedHashSet(LinkedHashSet<String> linkedHashSet, String string) {
int index = -1;
Iterator<String> linkedSetStringIt = linkedHashSet.iterator();
while (linkedSetStringIt.hasNext()) {
index++;
String temp = linkedSetStringIt.next();
if (temp.equals(string)) {
return index;
}
}
return -1;
}
private static void convertAndAddImport(LinkedHashSet<Import> allImports, List<Node> thisImport,
String eol) {
boolean isStatic = false;
String importItem = null;
String prefix = "";
String suffix = "";
for (Node n : thisImport) {
if (n instanceof Comment) {
if (importItem == null) {
prefix += n.toString();
} else {
suffix += n.toString();
}
}
if (n instanceof ImportDeclaration) {
ImportDeclaration i = (ImportDeclaration) n;
isStatic = i.isStatic();
importItem = i.getName().asString() + (i.isAsterisk() ? ".*" : "");
}
}
suffix = suffix.trim();
if (!suffix.isEmpty()) {
suffix = " " + suffix;
}
Import imp = new Import(isStatic, importItem, prefix.trim(), suffix, eol);
Iterator<Import> iter = allImports.iterator();
// this de-duplication can probably be made more efficient by doing it all at the end
while (iter.hasNext()) {
Import candidate = iter.next(); // potential duplicate
if (candidate.isDuplicatedBy(imp)) {
iter.remove();
imp = candidate.combineWith(imp);
}
}
allImports.add(imp);
}
private Set<Binding> internalGetGuiceBindings(Grammar grammar, Function<IGeneratorFragment, Set<Binding>> func) {
LinkedHashSet<Binding> bindings = new LinkedHashSet<Binding>();
for (IGeneratorFragment module : fragments) {
Set<Binding> temp = func.apply(module);
if (temp != null) {
for (Binding entry : temp) {
if (bindings.contains(entry)) {
for (Iterator<Binding> iterator = bindings.iterator(); iterator.hasNext();) {
Binding binding = iterator.next();
if (binding.equals(entry)) {
if (binding.isFinal()) {
if (entry.isFinal()) {
throw new IllegalStateException("Conflicting final bindings for '" + binding.getKey() + "' from fragments " +
""+binding.getContributedBy()+" and "+entry.getContributedBy());
} else {
LOG.warn("Cannot override final binding '" + binding + "'. " +
"Ignoring binding from fragment '"+getModuleClassName(module) +"'");
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("replacing binding : " + binding);
LOG.debug(" with new binding : " + entry);
}
iterator.remove();
}
break;
}
}
}
bindings.add(entry);
}
}
}
return bindings;
}
@Override
public Iterator<String> getParameterNamesIterator() {
// We need to compute the set of all param names in advance
// So we don't wind up with an iterator that returns the same
// String more then once (SOLR-6780)
LinkedHashSet<String> allKeys = new LinkedHashSet<>();
for (SolrParams p : new SolrParams [] {params, defaults}) {
Iterator<String> localKeys = p.getParameterNamesIterator();
while (localKeys.hasNext()) {
allKeys.add(localKeys.next());
}
}
return allKeys.iterator();
}
/**
* Test {@link
* OWLGraphWrapperEdgesExtended#
* getSubAnnotationPropertyReflexiveClosureOf(OWLAnnotationProperty)}.
*/
@Test
public void shouldGetSubAnnotationPropertyReflexiveClosureOf() {
Set<OWLAnnotationProperty> expectedSubprops = new HashSet<OWLAnnotationProperty>();
expectedSubprops.add(subsetProp);
expectedSubprops.add(groupProp);
expectedSubprops.add(fake1Prop);
expectedSubprops.add(fake2Prop);
LinkedHashSet<OWLAnnotationProperty> subprops =
wrapper.getSubAnnotationPropertyReflexiveClosureOf(subsetProp);
assertEquals("Incorrect sub-properties returned", expectedSubprops,
subprops);
Iterator<OWLAnnotationProperty> iterator = subprops.iterator();
assertEquals("Incorrect order for sub-properties", subsetProp,
iterator.next());
assertEquals("Incorrect order for sub-properties", groupProp,
iterator.next());
expectedSubprops = new HashSet<OWLAnnotationProperty>();
expectedSubprops.add(groupProp);
expectedSubprops.add(fake1Prop);
expectedSubprops.add(fake2Prop);
subprops =
wrapper.getSubAnnotationPropertyReflexiveClosureOf(groupProp);
assertEquals("Incorrect sub-properties returned", expectedSubprops,
subprops);
assertEquals("Incorrect order for sub-properties", groupProp,
subprops.iterator().next());
expectedSubprops = new HashSet<OWLAnnotationProperty>();
expectedSubprops.add(lonelyProp);
assertEquals("Incorrect sub-properties returned", expectedSubprops,
wrapper.getSubAnnotationPropertyReflexiveClosureOf(lonelyProp));
}
public void concreteWriteReadLinkedPos1Test(){
String tainted = TelephonyManager.getDeviceId();
LinkedHashSet<String> set = new LinkedHashSet<String>();
set.add("neutral");
set.add(tainted);
Iterator<String> it = set.iterator();
it.next();
String taintedElement2 = it.next();
ConnectionManager cm = new ConnectionManager();
cm.publish(taintedElement2);
}
private void processExpirationQueue(long now, LinkedHashSet<Claim> queue) {
Iterator<Claim> claimIter = queue.iterator();
while (claimIter.hasNext()) {
Claim claim = claimIter.next();
// If the claim at the head of the queue hasn't expired yet, we're done processing this queue.
if (claim.getExpireAt() > now) {
break;
}
_claimMap.remove(claim);
claimIter.remove();
}
}
@Test
public void testGaugeOrdering() throws Exception {
DataGeneratorFactory factory =
new DataGeneratorFactoryBuilder(context, DataGeneratorFormat.WHOLE_FILE).build();
factory.getGenerator(new ByteArrayOutputStream());
Gauge<Map<String, Object>> gauge = context.getGauge(FileRefUtil.fileStatisticGaugeName(context));
Map<String, Object> map = gauge.getValue();
LinkedHashSet<String> hashSet = new LinkedHashSet<>();
//Ordering
hashSet.add(FileRefUtil.FILE);
hashSet.add(FileRefUtil.TRANSFER_THROUGHPUT);
hashSet.add(FileRefUtil.SENT_BYTES);
hashSet.add(FileRefUtil.REMAINING_BYTES);
hashSet.add(FileRefUtil.COMPLETED_FILE_COUNT);
Iterator<String> hashSetKeyIterator = hashSet.iterator();
Iterator<String> keySetIterator = map.keySet().iterator();
while (hashSetKeyIterator.hasNext()) {
Assert.assertEquals(hashSetKeyIterator.next(), keySetIterator.next());
}
hashSetKeyIterator = hashSet.iterator();
Iterator<Map.Entry<String, Object>> entrySetIterator = map.entrySet().iterator();
while (hashSetKeyIterator.hasNext()) {
Assert.assertEquals(hashSetKeyIterator.next(), entrySetIterator.next().getKey());
}
}
@Nullable
private LookupElement[] createLookupItems(String name, Editor editor, PsiNamedElement psiVariable) {
TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
if (psiVariable != null) {
final TextResult insertedValue =
templateState != null ? templateState.getVariableValue(PRIMARY_VARIABLE_NAME) : null;
if (insertedValue != null) {
final String text = insertedValue.getText();
if (!text.isEmpty() && !Comparing.strEqual(text, name)) {
final LinkedHashSet<String> names = new LinkedHashSet<String>();
names.add(text);
for (NameSuggestionProvider provider : Extensions.getExtensions(NameSuggestionProvider.EP_NAME)) {
final SuggestedNameInfo suggestedNameInfo = provider.getSuggestedNames(psiVariable, psiVariable, names);
if (suggestedNameInfo != null &&
provider instanceof PreferrableNameSuggestionProvider &&
!((PreferrableNameSuggestionProvider)provider).shouldCheckOthers()) {
break;
}
}
final LookupElement[] items = new LookupElement[names.size()];
final Iterator<String> iterator = names.iterator();
for (int i = 0; i < items.length; i++) {
items[i] = LookupElementBuilder.create(iterator.next());
}
return items;
}
}
}
return myLookupItems;
}
@Test
public void testMessageDeleiveredInCorrectOrder() throws Exception {
final LinkedHashSet<Message> received = new LinkedHashSet<>();
final LinkedHashSet<Message> beforeRollback = new LinkedHashSet<>();
final LinkedHashSet<Message> afterRollback = new LinkedHashSet<>();
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(destinationName);
MessageConsumer consumer = session.createConsumer(destination);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
received.add(message);
}
});
sendMessages();
session.commit();
connection.start();
assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
LOG.info("Consumer has received " + received.size() + " messages.");
return received.size() == MSG_COUNT;
}
}));
beforeRollback.addAll(received);
received.clear();
session.rollback();
assertTrue("Post-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
LOG.info("Consumer has received " + received.size() + " messages since rollback.");
return received.size() == MSG_COUNT;
}
}));
afterRollback.addAll(received);
received.clear();
assertEquals(beforeRollback.size(), afterRollback.size());
assertEquals(beforeRollback, afterRollback);
Iterator<Message> after = afterRollback.iterator();
Iterator<Message> before = beforeRollback.iterator();
while (before.hasNext() && after.hasNext()) {
TextMessage original = (TextMessage) before.next();
TextMessage rolledBack = (TextMessage) after.next();
int originalInt = Integer.parseInt(original.getText());
int rolledbackInt = Integer.parseInt(rolledBack.getText());
assertEquals(originalInt, rolledbackInt);
}
session.commit();
}
/**
* Given a collection of Accumulo {@link Authorizations} objects, this method
* attempts to compute a "minimum" set that can be used for a multi-entity scan
* of data from Accumulo. The idea is that there is a call chain with multiple
* entities (e.g., a middleware broker acting on behalf of a GUI that is in turn
* acting on behalf of a user). In order to ensure that only data visible to all
* of the entities is returned, we must add a visibility filter for each entity
* in the chain to ensure that each key/value pair returned by Accumulo can be
* seen by all of the entities in the chain. Since we may be scanning a very
* large number of keys, it would be ideal if we could reduce the number of
* visibility filters to a small set if that can be done safely.
* <p>
* The crux of the problem, and the reason we need multiple filters in the first
* place (as opposed to just intersecting the authorizations for all all
* entities and using that set), is the fact that Accumulo visibility
* expressions may include disjunctions. Consider the following visibility
* expression.
* <p>
* {@code (A & B & ORG1) | (A & C & ORG2)}
* <p>
* If the incoming user has the Accumulo authorizations A, B, and ORG1 and the
* user is coming through a server with the Accumulo authorizations A, C, and
* ORG2, then the server is allowed to see data protected with this expression
* and the user is also allowed, so the data should be returned with those two
* calling entities. If we simply computed an intersection of the authorizations
* that set would be A. That set of authorizations does not match the visibility
* expression and data that should be returned would not be.
* <p>
* Given that we must apply multiple visibility filters in order to properly
* return data for a calling entity chain, it is desirable to minimize the
* number of visibility filters used, if possible. If a set of authorizations is
* a superset of any other set of authorizations, then it does not need to be
* tested. As long as we are not changing any of the authorizations sets, we
* know we will never allow any data to be returned that would otherwise not be.
* By removing authorizations sets, we might only prevent the return of data
* that should otherwise be returned. Consider a given set of authorizations
* that is a subset of another. If the subset passes a visibility expression,
* then the superset will too since it contains at least the same
* authorizations, so there is no need to test against it. If the subset does
* not pass, then the data is not visible to the chain anyway, so there is no
* point in testing the superset.
*
* @param authorizations
* the list of Authorizations for each entity in the call chain
* @return a minimized set of Authorizations that allows visibility of exactly
* the same data as {@code authorizations}
*/
public static Collection<Authorizations> minimize(Collection<Authorizations> authorizations) {
if (authorizations.size() > 1) {
// Convert collection of Authorizations into a collection of String sets (the
// individual authorizations).
// Since we are adding to a LinkedHashSet, this will de-dupe any duplicate
// authorization sets.
final LinkedHashSet<Set<String>> allAuths = authorizations.stream().map(
a -> a.getAuthorizations().stream().map(String::new).collect(Collectors.toCollection(HashSet::new)))
.collect(Collectors.toCollection(LinkedHashSet::new));
// Go through the authorizations sets and remove any that are supersets of any
// other.
for (Iterator<Set<String>> it = allAuths.iterator(); it.hasNext(); /* empty */) {
Set<String> currentSet = it.next();
if (allAuths.stream().filter(a -> a != currentSet && a.size() <= currentSet.size())
.anyMatch(currentSet::containsAll))
it.remove();
}
// If we removed any sets of authorizations, then we need to convert the reduced
// set from
// TreeSet<String> objects back into Authorizations objects.
if (allAuths.size() < authorizations.size()) {
authorizations = allAuths.stream().map(a -> new Authorizations(a.toArray(new String[0])))
.collect(Collectors.toCollection(LinkedHashSet::new));
}
}
return authorizations;
}