List of usage examples for java.util Iterator Iterator
Iterator
From source file:org.apache.stanbol.enhancer.nlp.model.impl.SectionImpl.java
/** * Iterator that does not throw {@link ConcurrentModificationException} but * considers modifications to the underlying set by using the * {@link NavigableMap#higherKey(Object)} method for iterating over the * Elements!<p>/*from ww w . ja v a2s .c o m*/ * This allows to add new {@link Span}s to the {@link Section} while * iterating (e.g. add {@link Token}s and/or {@link Chunk}s while iterating * over the {@link Sentence}s of an {@link AnalysedText}) * @param section the (sub-)section of the current section to iterate or * <code>null</code> to iterate the whole section. * @return the iterator */ protected Iterator<Span> getIterator(final SubSetHelperSpan section) { //create a virtual Span with the end of the section to iterate over final Span end = new SubSetHelperSpan(section == null ? getEnd() : //if no section is defined use the parent section.getEnd()); //use the end of the desired section return new Iterator<Span>() { boolean init = false; boolean removed = true; //init with the first span of the iterator private Span span = section == null ? SectionImpl.this : section; @Override public boolean hasNext() { return getNext() != null; } private Span getNext() { Span next = context.spans.higherKey(span); return next == null || next.compareTo(end) >= 0 ? null : next; } @Override public Span next() { init = true; span = getNext(); removed = false; if (span == null) { throw new NoSuchElementException(); } return span; } @Override public void remove() { if (!init) { throw new IllegalStateException("remove can not be called before the first call to next"); } if (removed) { throw new IllegalStateException("the current Span was already removed!"); } context.spans.remove(span); removed = true; } }; }
From source file:org.commonjava.cartographer.graph.spi.neo4j.model.Neo4jGraphPath.java
@Override public Iterator<Long> iterator() { return new Iterator<Long>() { private int next = 0; @Override//w w w.j av a2 s .c o m public boolean hasNext() { return relationships.length > next; } @Override public Long next() { return relationships[next++]; } @Override public void remove() { throw new UnsupportedOperationException( "Immutable array of relationship ID's. Remove not supported."); } }; }
From source file:org.jiemamy.entity.io.meta.EntityMeta.java
/** * ???{@link Iterable}??//www. jav a 2 s . c om * * @return ???{@link Iterable} */ public Iterable<PropertyMeta> getAllPropertyMeta() { return new Iterable<PropertyMeta>() { public Iterator<PropertyMeta> iterator() { return new Iterator<PropertyMeta>() { private int i; public boolean hasNext() { return i < propertyMetas.size(); } public PropertyMeta next() { return propertyMetas.get(i++); } public void remove() { throw new UnsupportedOperationException(); } }; } }; }
From source file:ListOrderedMap.java
public Set entrySet() { return new AbstractSet() { Set delegate = ListOrderedMap.this.map.entrySet(); public int size() { return ListOrderedMap.this.size(); }/*from w ww .ja v a 2 s .c om*/ public boolean contains(Object obj) { return delegate.contains(obj); } public boolean remove(Object obj) { boolean result = contains(obj); if (result) { ListOrderedMap.this.remove(((Map.Entry) obj).getKey()); } return result; } public void clear() { ListOrderedMap.this.clear(); } public boolean equals(Object obj) { return obj == this ? true : delegate.equals(obj); } public int hashCode() { return delegate.hashCode(); } public String toString() { return delegate.toString(); } public Iterator iterator() { return new Iterator() { Iterator keys = lst.iterator(); Object last = null; public Object next() { last = keys.next(); return new Map.Entry() { Object key = last; public Object getKey() { return key; } public Object getValue() { return map.get(key); } public Object setValue(Object value) { return map.put(key, value); } }; } public boolean hasNext() { return keys.hasNext(); } public void remove() { keys.remove(); map.remove(last); } }; } }; }
From source file:org.apache.hadoop.hbase.thrift.CallQueue.java
@Override public Iterator<Runnable> iterator() { return new Iterator<Runnable>() { final Iterator<Call> underlyingIterator = underlyingQueue.iterator(); @Override/*ww w . j a va 2 s. c o m*/ public Runnable next() { return underlyingIterator.next(); } @Override public boolean hasNext() { return underlyingIterator.hasNext(); } @Override public void remove() { underlyingIterator.remove(); } }; }
From source file:MiniMap.java
/** * @see java.util.Map#keySet()/*from w ww . j a va2s . com*/ */ public Set<K> keySet() { return new AbstractSet<K>() { @Override public Iterator<K> iterator() { return new Iterator<K>() { public boolean hasNext() { return i < size - 1; } public K next() { // Just in case... (WICKET-428) if (!hasNext()) { throw new NoSuchElementException(); } // Find next key i = nextKey(nextIndex(i)); // Get key return keys[i]; } public void remove() { keys[i] = null; values[i] = null; size--; } int i = -1; }; } @Override public int size() { return size; } }; }
From source file:com.act.lcms.LCMSNetCDFParser.java
@Override public Iterator<LCMSSpectrum> getIterator(String inputFile) throws ParserConfigurationException, IOException, XMLStreamException { final NetcdfFile netcdfFile = NetcdfFile.open(inputFile); // Assumption: all referenced Variables will always exist in the NetcdfFfile. // Assumption: these arrays will have the same length. final Array mzValues = netcdfFile.findVariable(MASS_VALUES).read(); final Array intensityValues = netcdfFile.findVariable(INTENSITY_VALUES).read(); assert (mzValues.getSize() == intensityValues.getSize()); // Assumption: the mz/intensity values are always floats. assert (mzValues.getDataType() == DataType.FLOAT && intensityValues.getDataType() == DataType.FLOAT); // Assumption: all of these variables' arrays will have the same lengths. final Array scanTimeArray = netcdfFile.findVariable(SCAN_TIME).read(); final Array scanPointsStartArray = netcdfFile.findVariable(SCAN_POINTS_START).read(); final Array scanPointsCountArray = netcdfFile.findVariable(SCAN_POINTS_COUNT).read(); final Array totalIntensityArray = netcdfFile.findVariable(TOTAL_INTENSITY).read(); assert (scanTimeArray.getSize() == scanPointsStartArray.getSize() && scanPointsStartArray.getSize() == scanPointsCountArray.getSize() && scanPointsCountArray.getSize() == totalIntensityArray.getSize()); // Assumption: the following four columns always have these types. assert (scanTimeArray.getDataType() == DataType.DOUBLE && scanPointsStartArray.getDataType() == DataType.INT && scanPointsCountArray.getDataType() == DataType.INT && totalIntensityArray.getDataType() == DataType.DOUBLE); final long size = scanTimeArray.getSize(); return new Iterator<LCMSSpectrum>() { private int i = 0; @Override/* ww w .j av a 2s . co m*/ public boolean hasNext() { return this.i < size; } @Override public LCMSSpectrum next() { int pointCount = scanPointsCountArray.getInt(i); List<Pair<Double, Double>> mzIntPairs = new ArrayList<>(pointCount); int pointsStart = scanPointsStartArray.getInt(i); int pointsEnd = pointsStart + pointCount; for (int p = pointsStart; p < pointsEnd; p++) { Double mz = Float.valueOf(mzValues.getFloat(p)).doubleValue(); Double intensity = Float.valueOf(intensityValues.getFloat(p)).doubleValue(); mzIntPairs.add(Pair.of(mz, intensity)); } LCMSSpectrum s = new LCMSSpectrum(i, scanTimeArray.getDouble(i), "s", mzIntPairs, null, null, null, i, totalIntensityArray.getDouble(i)); // Don't forget to advance the counter! this.i++; // Close the file if we're done with all the array contents. if (i >= size) { try { netcdfFile.close(); } catch (IOException e) { throw new RuntimeException(e); // TODO: can we do better? } } return s; } }; }
From source file:org.apache.hadoop.metrics2.sink.timeline.HadoopTimelineMetricsSinkTest.java
@Test public void testDuplicateTimeSeriesNotSaved() throws Exception { HadoopTimelineMetricsSink sink = createMockBuilder(HadoopTimelineMetricsSink.class).withConstructor() .addMockedMethod("appendPrefix").addMockedMethod("emitMetrics").createNiceMock(); SubsetConfiguration conf = createNiceMock(SubsetConfiguration.class); expect(conf.getString(eq("slave.host.name"))).andReturn("testhost").anyTimes(); expect(conf.getParent()).andReturn(null).anyTimes(); expect(conf.getPrefix()).andReturn("service").anyTimes(); expect(conf.getString(eq(COLLECTOR_HOST_PROPERTY))).andReturn("localhost:63188").anyTimes(); expect(conf.getString(eq("serviceName-prefix"), eq(""))).andReturn("").anyTimes(); expect(conf.getInt(eq(MAX_METRIC_ROW_CACHE_SIZE), anyInt())).andReturn(10).anyTimes(); // Return eviction time smaller than time diff for first 3 entries // Third entry will result in eviction expect(conf.getInt(eq(METRICS_SEND_INTERVAL), anyInt())).andReturn(10).anyTimes(); conf.setListDelimiter(eq(',')); expectLastCall().anyTimes();/* w ww .ja va2 s .co m*/ expect(conf.getKeys()).andReturn(new Iterator() { @Override public boolean hasNext() { return false; } @Override public Object next() { return null; } @Override public void remove() { } }).once(); AbstractMetric metric = createNiceMock(AbstractMetric.class); expect(metric.name()).andReturn("metricName").anyTimes(); expect(metric.value()).andReturn(1.0).once(); expect(metric.value()).andReturn(2.0).once(); expect(metric.value()).andReturn(3.0).once(); expect(metric.value()).andReturn(4.0).once(); expect(metric.value()).andReturn(5.0).once(); expect(metric.value()).andReturn(6.0).once(); MetricsRecord record = createNiceMock(MetricsRecord.class); expect(record.name()).andReturn("testName").anyTimes(); expect(record.context()).andReturn("testContext").anyTimes(); sink.appendPrefix(eq(record), (StringBuilder) anyObject()); expectLastCall().anyTimes().andStubAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { return null; } }); final Long now = System.currentTimeMillis(); // TODO: Current implementation of cache needs > 1 elements to evict any expect(record.timestamp()).andReturn(now).times(2); expect(record.timestamp()).andReturn(now + 100l).times(2); expect(record.timestamp()).andReturn(now + 200l).once(); expect(record.timestamp()).andReturn(now + 300l).once(); expect(record.metrics()).andReturn(Arrays.asList(metric)).anyTimes(); final List<TimelineMetrics> capturedMetrics = new ArrayList<TimelineMetrics>(); sink.emitMetrics((TimelineMetrics) anyObject()); expectLastCall().andStubAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { capturedMetrics.add((TimelineMetrics) EasyMock.getCurrentArguments()[0]); return null; } }); replay(conf, sink, record, metric); sink.init(conf); // time = t1 sink.putMetrics(record); // time = t1 sink.putMetrics(record); // time = t2 sink.putMetrics(record); // Evict // time = t2 sink.putMetrics(record); // time = t3 sink.putMetrics(record); // time = t4 sink.putMetrics(record); verify(conf, sink, record, metric); Assert.assertEquals(2, capturedMetrics.size()); Iterator<TimelineMetrics> metricsIterator = capturedMetrics.iterator(); // t1, t2 TimelineMetric timelineMetric1 = metricsIterator.next().getMetrics().get(0); Assert.assertEquals(2, timelineMetric1.getMetricValues().size()); Iterator<Long> timestamps = timelineMetric1.getMetricValues().keySet().iterator(); Assert.assertEquals(now, timestamps.next()); Assert.assertEquals(new Long(now + 100l), timestamps.next()); Iterator<Double> values = timelineMetric1.getMetricValues().values().iterator(); Assert.assertEquals(new Double(1.0), values.next()); Assert.assertEquals(new Double(3.0), values.next()); // t3, t4 TimelineMetric timelineMetric2 = metricsIterator.next().getMetrics().get(0); Assert.assertEquals(2, timelineMetric2.getMetricValues().size()); timestamps = timelineMetric2.getMetricValues().keySet().iterator(); Assert.assertEquals(new Long(now + 200l), timestamps.next()); Assert.assertEquals(new Long(now + 300l), timestamps.next()); values = timelineMetric2.getMetricValues().values().iterator(); Assert.assertEquals(new Double(5.0), values.next()); Assert.assertEquals(new Double(6.0), values.next()); }
From source file:corner.orm.gae.impl.GaeCachedEntityServiceImpl.java
/** * @see corner.orm.gae.impl.JpaEntityServiceImpl#find(java.lang.Class, java.lang.Object, java.lang.String, int, int) *//*w ww . j a v a 2s . co m*/ @Override public <T> Iterator<T> find(final Class<T> persistClass, Object conditions, String order, int start, int offset) { //ID? final Iterator ids = super.find(persistClass, conditions, order, start, offset); return new Iterator() { @Override public boolean hasNext() { return ids.hasNext(); } @Override public Object next() { Object id = ids.next(); return get(persistClass, id); } @Override public void remove() { ids.remove(); } }; }
From source file:ca.uhn.fhir.parser.BaseParser.java
protected Iterable<CompositeChildElement> compositeChildIterator(IBase theCompositeElement, final boolean theContainedResource, final CompositeChildElement theParent) { BaseRuntimeElementCompositeDefinition<?> elementDef = (BaseRuntimeElementCompositeDefinition<?>) myContext .getElementDefinition(theCompositeElement.getClass()); final List<BaseRuntimeChildDefinition> children = elementDef.getChildrenAndExtension(); return new Iterable<BaseParser.CompositeChildElement>() { @Override//from w w w .j a va2s. c om public Iterator<CompositeChildElement> iterator() { return new Iterator<CompositeChildElement>() { private Iterator<? extends BaseRuntimeChildDefinition> myChildrenIter; private Boolean myHasNext = null; private CompositeChildElement myNext; /** * Constructor */ { myChildrenIter = children.iterator(); } @Override public boolean hasNext() { if (myHasNext != null) { return myHasNext; } myNext = null; do { if (myChildrenIter.hasNext() == false) { myHasNext = Boolean.FALSE; return false; } myNext = new CompositeChildElement(theParent, myChildrenIter.next()); /* * There are lots of reasons we might skip encoding a particular child */ if (myNext.getDef().getElementName().equals("id")) { myNext = null; } else if (!myNext.shouldBeEncoded()) { myNext = null; } else if (isSummaryMode() && !myNext.getDef().isSummary()) { myNext = null; } else if (myNext.getDef() instanceof RuntimeChildNarrativeDefinition) { if (isSuppressNarratives() || isSummaryMode()) { myNext = null; } else if (theContainedResource) { myNext = null; } } else if (myNext.getDef() instanceof RuntimeChildContainedResources) { if (theContainedResource) { myNext = null; } } } while (myNext == null); myHasNext = true; return true; } @Override public CompositeChildElement next() { if (myHasNext == null) { if (!hasNext()) { throw new IllegalStateException(); } } CompositeChildElement retVal = myNext; myNext = null; myHasNext = null; return retVal; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; }