Java Code Examples for java.util.Iterator

The following are top voted examples for showing how to use java.util.Iterator. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: sphereMiners   File: DumbMiner.java View source code 19 votes vote down vote up
private void updateTargetedDots() {
    Iterator<Sphere> it = alreadyTargetedDots.keySet().iterator();
    while (it.hasNext()) {
        Sphere dot = it.next();
        if (!dots.contains(dot)) {
            it.remove();
        }
    }
}
 
Example 2
Project: sphereMiners   File: DumbMiner.java View source code 9 votes vote down vote up
private void fetchDots(Sphere ownSphere) {
    // don't change direction if already on the way
    if (alreadyTargetedDots.containsValue(ownSphere)) {
        return;
    }

    Iterator<Sphere> dotsIt = dots.iterator();
    Sphere nextDot = dotsIt.next();
    double minDist = ownSphere.getPosition().dist(nextDot.getPosition());
    while (dotsIt.hasNext()) {
        Sphere dot = dotsIt.next();
        // only go to dots that are not already targeted
        if (!alreadyTargetedDots.containsKey(dot)) {
            double tmpDist = ownSphere.getPosition().dist(dot.getPosition());
            if (tmpDist < minDist) {
                minDist = tmpDist;
                nextDot = dot;
            }
        }
    }
    final Position moveTo = nextDot.getPosition().sub(ownSphere.getPosition());
    alreadyTargetedDots.put(nextDot, ownSphere);
    newDirections.put(ownSphere, moveTo);
}
 
Example 3
Project: jena   File: UpdateEngineWorker.java View source code 9 votes vote down vote up
protected void execDelete(List<Quad> onceQuads, List<Quad> templateQuads, Node dftGraph, Iterator<Binding> bindings) {
    if ( onceQuads != null && bindings.hasNext() )
        // If at least once.
        onceQuads.forEach(datasetGraph::delete);
    Iterator<Quad> it = template(templateQuads, dftGraph, bindings) ;
    if ( it == null ) return ;
    it.forEachRemaining(datasetGraph::delete) ;
}
 
Example 4
Project: jentrata-msh   File: PartnershipPageletAdaptor.java View source code 8 votes vote down vote up
public Hashtable getHashtable(HttpServletRequest request)
        throws FileUploadException, IOException {
    Hashtable ht = new Hashtable();
    DiskFileUpload upload = new DiskFileUpload();
    List fileItems = upload.parseRequest(request);
    Iterator iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            ht.put(item.getFieldName(), item.getString());
        } else {
            if (item.getName().equals("")) {
                //ht.put(item.getFieldName(), null);
            } else if (item.getSize() == 0) {
                //ht.put(item.getFieldName(), null);
            } else {
                ht.put(item.getFieldName(), item.getInputStream());
            }
        }
    }
    return ht;
}
 
Example 5
Project: plugz   File: DescriptorHandlerService.java View source code 8 votes vote down vote up
private void findHandlers(
        Map<IDescriptorFinderParameters, IDescriptorIOHandler> map) {
    final Iterator<IDescriptorIOHandler> handlers =
            this.spiFacade.load(IDescriptorIOHandler.class);
    handlers.forEachRemaining(handler -> {
        map.put(handler.getParameters(), handler);
        LOGGER.trace("Indexing descriptor handler for {}", handler.getParameters());
    });
}
 
Example 6
Project: nikeplus-fuelband-se-reversed   File: MainActivity.java View source code 7 votes vote down vote up
private void dumpServices( BluetoothGatt gatt )
{
	for( BluetoothGattService svc : gatt.getServices() )
   	{
   		String svc_uuid = svc.getUuid().toString(),
   			   svc_name = GATTAttributes.lookup( svc_uuid, "" );
   		Logger.d( "SERVICE " + svc_name + " ( " + svc_uuid + " )" );
   		
   		for( BluetoothGattCharacteristic chara : svc.getCharacteristics() )
   		{
   			String chr_uuid = chara.getUuid().toString(),
   				   chr_name = GATTAttributes.lookup( chr_uuid, "" );
   			int chr_props = chara.getProperties();
   			String props = "";
   			
   			Iterator it = propsMap.entrySet().iterator();
   			while( it.hasNext() ){
   				Map.Entry pairs = (Map.Entry)it.next();
   				
   				if( ( chr_props & (Integer)pairs.getKey() ) != 0 ){
   					props += pairs.getValue().toString() + " ";
   				}
   			}
   			
       		Logger.d( "    " + chr_name + " ( " + chr_uuid + " ) [" + props + "] : " + Utils.bytesToHex(chara.getValue() ) );
       		
       		for( BluetoothGattDescriptor desc : chara.getDescriptors() )
       		{
       			Logger.d( "      DESC: " + desc.getUuid() );
       		}
   		}
   	}
	
	Logger.d( "---------------------------------------------------------------------------" );
}
 
Example 7
Project: raylew_algorithm   File: ????.java View source code 7 votes vote down vote up
public static void main(String[] args) {
    String str = "zdsgzd";
    Map map = new HashMap();
    int maxvalue = 0;
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (map.get(c) == null) {
            map.put(c, 1);
        } else {
            int total =(Integer) map.get(c);
            total++;
            map.put(c, total);
            if (maxvalue < total) {
                maxvalue = total;
            }
        }
    }
    System.out.println("maxvalue:" + maxvalue);
    System.out.println(map.toString());
    Set set = map.keySet();
    Iterator iterator = set.iterator();
    int max = 0;
    char maxkey = 0;
    char key = 0;
    while (iterator.hasNext()) {
        key = (Character) iterator.next();
        if (max <= (Integer) map.get(key)) {
            max = (Integer) map.get(key);
            maxkey = key;
        }
    }
    System.out.println(maxkey + ":" + max);
}
 
Example 8
Project: JAME   File: NavigationModel.java View source code 7 votes vote down vote up
/**
 * @param c
 */
public void setComponent(final Component c) {
	int i = 0;
	final Iterator<Component> it = history.iterator();
	while (it.hasNext()) {
		if ((it.next() == c) || (i > index)) {
			it.remove();
			while (it.hasNext()) {
				it.next();
				it.remove();
			}
			break;
		}
		i += 1;
	}
	history.add(c);
	index = history.size() - 1;
	container.loadComponent(history.get(index), 0);
	fireStateChanged(event);
}
 
Example 9
Project: virgo.kernel   File: ServiceRegistryConverterRegistry.java View source code 7 votes vote down vote up
private void serviceUnregistering(ServiceReference<?> serviceReference) {
    Object converter = this.bundleContext.getService(serviceReference);
    if (converter != null) {
        synchronized (monitor) {
            Iterator<Entry<String, Converter>> iterator = this.converters.entrySet().iterator();
            while (iterator.hasNext()) {
                Converter candidate = iterator.next().getValue();
                if (converter.equals(candidate)) {
                    iterator.remove();
                }
            }                
        }
    }
}
 
Example 10
Project: revapi   File: Util.java View source code 7 votes vote down vote up
@Override
public Void visitIntersection(IntersectionType t, StringBuilderAndState<TypeMirror> state) {
    Iterator<? extends TypeMirror> it = IgnoreCompletionFailures.in(t::getBounds).iterator();
    if (it.hasNext()) {
        it.next().accept(this, state);
    }

    TypeVisitor<Void, StringBuilderAndState<TypeMirror>> me = this;

    it.forEachRemaining(b -> { state.bld.append(", "); b.accept(me, state); });

    return null;
}
 
Example 11
Project: lettuce   File: ClusterSlotsParser.java View source code 6 votes vote down vote up
private static ClusterSlotRange parseRange(List<?> range) {
    Iterator<?> iterator = range.iterator();

    int from = Ints.checkedCast(getLongFromIterator(iterator, 0));
    int to = Ints.checkedCast(getLongFromIterator(iterator, 0));
    HostAndPort master = null;

    List<HostAndPort> slaves = Lists.newArrayList();
    if (iterator.hasNext()) {
        master = getHostAndPort(iterator);
    }

    while (iterator.hasNext()) {
        HostAndPort slave = getHostAndPort(iterator);
        if (slave != null) {
            slaves.add(slave);
        }
    }

    return new ClusterSlotRange(from, to, master, Collections.unmodifiableList(slaves));
}
 
Example 12
Project: lettuce   File: ClusterSlotsParser.java View source code 6 votes vote down vote up
private static long getLongFromIterator(Iterator<?> iterator, long defaultValue) {
    if (iterator.hasNext()) {
        Object object = iterator.next();
        if (object instanceof String) {
            return Long.parseLong((String) object);
        }

        if (object instanceof Number) {
            return ((Number) object).longValue();
        }
    }
    return defaultValue;
}
 
Example 13
Project: jentrata-msh   File: PartnershipPageletAdaptor.java View source code 6 votes vote down vote up
/**
 * @return
 * @throws DAOException
 */
private void getAllPartnerships(PropertyTree dom) throws DAOException {

    PartnershipDAO partnershipDAO = (PartnershipDAO) EbmsProcessor.core.dao
            .createDAO(PartnershipDAO.class);

    Iterator i = partnershipDAO.findAllPartnerships().iterator();
    for (int pi = 1; i.hasNext(); pi++) {
        PartnershipDVO partnershipDVO = (PartnershipDVO) i.next();
        dom.setProperty("partnership[" + pi + "]/partnership_id",
                partnershipDVO.getPartnershipId());
        dom.setProperty("partnership[" + pi + "]/cpa_id", partnershipDVO
                .getCpaId());
        dom.setProperty("partnership[" + pi + "]/service", partnershipDVO
                .getService());
        dom.setProperty("partnership[" + pi + "]/action_id", partnershipDVO
                .getAction());
    }
}
 
Example 14
Project: lettuce   File: ClusterSlotsParser.java View source code 6 votes vote down vote up
private static HostAndPort getHostAndPort(Iterator<?> iterator) {
    Object element = iterator.next();
    if (element instanceof List) {
        List<?> hostAndPortList = (List<?>) element;
        if (hostAndPortList.size() != 2) {
            return null;
        }

        Iterator<?> hostAndPortIterator = hostAndPortList.iterator();
        String host = (String) hostAndPortIterator.next();
        int port = Ints.checkedCast(getLongFromIterator(hostAndPortIterator, 0));
        HostAndPort hostAndPort = HostAndPort.fromParts(host, port);

        return hostAndPort;

    }
    return null;
}
 
Example 15
Project: aws-toolkit-eclipse   File: SimpleDBContentProviderExtension.java View source code 6 votes vote down vote up
public PipelinedShapeModification interceptAdd(final PipelinedShapeModification anAddModification) {
  //anAddModification.getChildren().clear();

  if (anAddModification.getParent() instanceof Database
      && DB_DEFINITION_VENDOR.equals(((Database) anAddModification.getParent()).getVendor())) {
    try {
      Database db = (Database) anAddModification.getParent();
      Schema schema = ((Schema) ((Catalog) db.getCatalogs().get(0)).getSchemas().get(0));

      anAddModification.getChildren().clear();
      IVirtualNode domains = VirtualNodeServiceFactory.INSTANCE.makeTableNode(DOMAINS, DOMAINS, db);
      domains.addChildren(schema.getTables());
      anAddModification.getChildren().add(domains);
    } catch (Exception e) {
      // strange broken tree, nothing to mangle
    }
  }

  if (anAddModification.getParent() instanceof Table) {
    Iterator it = anAddModification.getChildren().iterator();
    while (it.hasNext()) {
      Object o = it.next();
      if (!(o instanceof ColumnNode)) {
        it.remove();
      }
    }
  }

  if (anAddModification.getParent() instanceof Column) {
    anAddModification.getChildren().clear();
  }

  return anAddModification;
}
 
Example 16
Project: iswc2012metadata   File: DataInstance.java View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Set<Resource> getNamedTypes(){
	Set ret= this.m_model.listObjectsOfProperty(null, RDF.type).toSet();
	Iterator<RDFNode> iter = ret.iterator();
	while (iter.hasNext()){
		RDFNode node = iter.next();
		if (!node.isURIResource())
			iter.remove();
	}
	return ret;
}
 
Example 17
Project: dlna   File: DIDLObject.java View source code 6 votes vote down vote up
public DIDLObject replaceFirstProperty(Property property) {
    if (property == null) return this;
    Iterator<Property> it = getProperties().iterator();
    while (it.hasNext()) {
        Property p = it.next();
        if (p.getClass().isAssignableFrom(property.getClass()))
            it.remove();
    }
    addProperty(property);
    return this;
}
 
Example 18
Project: richfaces   File: FileUploadBean.java View source code 6 votes vote down vote up
public void clearFile() {
    System.out.println("Files to clear: " + this.clearedFile);
    Iterator<UploadedFile> i = files.iterator();
    while (i.hasNext()) {
        UploadedFile file = i.next();
        if (file.getName().equals(this.clearedFile)) {
            i.remove();
            break;
        }
    }
}
 
Example 19
Project: jlibs   File: Method.java View source code 6 votes vote down vote up
private File getFile(List<String>args, String argPrefix){
    File file = null;
    Iterator<String> iter = args.iterator();
    while(iter.hasNext()){
        String arg = iter.next();
        if(arg.startsWith(argPrefix)){
            iter.remove();
            file = Util.toFile(arg.substring(1));
        }
    }
    return file;
}
 
Example 20
Project: many-ql   File: QLFormDataStorage.java View source code 6 votes vote down vote up
/**
 * =====================
 * Public exposed getters
 * =====================
 */

public List<Question> getQuestions() {
    List<Question> questions = new ArrayList<>();
    Iterator<Question> iterator = this.questionsVisitor.getQuestions();

    // convert back to list
    // this way internal lists will not be modified by clients
    iterator.forEachRemaining(questions::add);
    return questions;
}
 
Example 21
Project: LazySeq   File: LazySeqIteratorTest.java View source code 6 votes vote down vote up
@Test
public void shouldCallConsumerForEachElementOfIteratorForFinitSeq() throws Exception {
	//given
	final Iterator<Character> iterator = of('a', 'b', 'c').iterator();

	//when
	iterator.forEachRemaining(consumerMock);

	//then
	verify(consumerMock).accept('a');
	verify(consumerMock).accept('b');
	verify(consumerMock).accept('c');
	verifyNoMoreInteractions(consumerMock);
}
 
Example 22
Project: BinaryOffheapHashMap   File: TestBOHMap.java View source code 6 votes vote down vote up
@Test
public void keySetIterator() {
    List<Binary> expectedKeys = new ArrayList<>();
    
    for (int i = 0; i < 100; i++) {
        byte[] key = new byte[8];
        byte[] value = new byte[8];

        random.nextBytes(key);
        random.nextBytes(value);

        if (map.put(new Binary(key), new Binary(value)) == null)
            expectedKeys.add(new Binary(key));
    }
    
    Iterator<Binary> iterator = map.keySet().iterator();
    List<Binary> actualKeys = new ArrayList<>();
    iterator.forEachRemaining(actualKeys::add);
    
    assertEquals(expectedKeys.size(), actualKeys.size());
    assertTrue(expectedKeys.containsAll(actualKeys));
}
 
Example 23
Project: ecgine   File: InstallPackageJob.java View source code 6 votes vote down vote up
/**
 * Find changes from existing installed version in organization
 * 
 * @param installed
 * @param installingVersion
 * @return
 */
private List<Change> findChanges(InstalledInstallingVersions version) {
	// Get UploadedPackageMemberships of existing installed version
	List<UploadedPackageMember> existingUPMs = getUploadedMembersByVersion(version.installed
			.getPackageVersion());

	// Get UploadedPackageMemberships of new installing version
	Iterator<UploadedPackageMember> newUPMs = getUploadedMembersByVersion(
			version.installing.getId()).iterator();

	List<Change> result = new ArrayList<>();

	// Find for Updated from previous Version
	while (newUPMs.hasNext()) {
		UploadedPackageMember upm = newUPMs.next();
		Optional<UploadedPackageMember> existingMembership = existingUPMs
				.stream()
				.filter(oupm -> oupm.getPackageMember() == upm
						.getPackageMember()).findAny();
		existingMembership.ifPresent(m -> {
			result.add(new Change(upm.getComponent(), m.getComponent()));
			existingUPMs.remove(m);
			newUPMs.remove();
		});
	}

	// Components left in newUMPs are all new memberships
	newUPMs.forEachRemaining(upm -> {
		result.add(new Change(upm.getComponent(), null));
	});

	// Components left in newUMPs are all deleted in current installing
	// version
	existingUPMs.forEach(upm -> {
		Change change = new Change(null, upm.getComponent());
		change.isDeleted = true;
		result.add(change);
	});

	return result;
}
 
Example 24
Project: openjdk8-jdk   File: SingletonIterator.java View source code 6 votes vote down vote up
public void testForEachRemaining() {
    Iterator<String> it = Collections.singleton("TheOne").iterator();
    AtomicInteger cnt = new AtomicInteger(0);

    it.forEachRemaining(s -> {
        assertEquals("TheOne", s);
        cnt.incrementAndGet();
    });

    assertEquals(cnt.get(), 1);
    assertFalse(it.hasNext());

    try {
        String str = it.next();
        fail("Should throw NoSuchElementException at end");
    } catch (NoSuchElementException ex) {
        // ignore;
    }
}
 
Example 25
Project: LanternServer   File: LanternChannelRegistrar.java View source code 6 votes vote down vote up
void sendPayloadToAll(String channel, Consumer<ByteBuf> payload) {
    checkNotNull(payload, "payload");
    Iterator<Player> players = this.server.getOnlinePlayers().stream().filter(
            player -> ((LanternPlayer) player).getConnection().getRegisteredChannels().contains(channel)).iterator();
    if (players.hasNext()) {
        ByteBuf buf = Unpooled.buffer();
        payload.accept(buf);
        Message msg = new MessagePlayInOutChannelPayload(channel, buf);
        players.forEachRemaining(player -> ((LanternPlayer) player).getConnection().send(msg));
    }
}
 
Example 26
Project: snap-desktop   File: ProductOpener.java View source code 6 votes vote down vote up
private static List<PluginEntry> getPluginsForFile(File file, DecodeQualification desiredQualification) {
    final Iterator<ProductReaderPlugIn> allReaderPlugIns = ProductIOPlugInManager.getInstance().getAllReaderPlugIns();
    final List<PluginEntry> possiblePlugIns = new ArrayList<>();
    allReaderPlugIns.forEachRemaining(plugIn -> {
        final DecodeQualification qualification = plugIn.getDecodeQualification(file);
        if (qualification == desiredQualification) {
            possiblePlugIns.add(new PluginEntry(plugIn, qualification));
        }
    });
    return possiblePlugIns;
}
 
Example 27
Project: peapod   File: FramedGraph.java View source code 6 votes vote down vote up
public <F, E extends Element> List<F> frame(Iterator<E> it, Class<F> clazz) {
    List<F> result = new ArrayList<>();
    it.forEachRemaining(e -> {
        IFramer<E, F> framer = registry.get(e, clazz);
        result.add(framer.frame(e, this));
    });
    return Collections.unmodifiableList(result);
}
 
Example 28
Project: dcache   File: PoolStatisticsV0.java View source code 6 votes vote down vote up
public void createDiffFile(File today, File yesterday, File resultFile) throws IOException {
    DataStore todayStore = new DataStore(today);

    Map<String, long[]> todayMap = todayStore.getLinearMap();

    Map<String, long[]> yesterdayMap = new DataStore(yesterday).getLinearMap();

    Map<String, long[]> resultMap    = new HashMap<>();

    for (Map.Entry<String, long[]> entry : todayMap.entrySet()) {
        String key = entry.getKey();
        long[] counter = entry.getValue();

        long[] result = new long[12];

        long[] yesterdayCounter = yesterdayMap.get(key);
        if (yesterdayCounter == null) {
            result[0] = -1;
            result[1] = -1;
        } else {
            result[0] = yesterdayCounter[0];
            result[1] = yesterdayCounter[1];
        }
        System.arraycopy(counter, 0, result, 2, 10);

        resultMap.put(key, result);
    }

    //noinspection ResultOfMethodCallIgnored
    resultFile.delete();

    try (PrintWriter pw = new PrintWriter(new FileWriter(resultFile))) {
        pw.println("#");
        Iterator<Map.Entry<String,Object>> it = todayStore.iterator();
        it.forEachRemaining(entry -> pw.println("# "+entry.getKey()+"="+entry.getValue()));
        pw.println("#");
        resultMap.entrySet().forEach(entry -> {
            pw.print(entry.getKey());
            for (long l : entry.getValue()) {
                pw.print(" ");
                pw.print(l);
            }
            pw.println("");
        });
    }
}
 
Example 29
Project: incubator-tinkerpop   File: ClusterCountMapReduce.java View source code 6 votes vote down vote up
@Override
public void reduce(final NullObject key, final Iterator<Serializable> values, final ReduceEmitter<NullObject, Integer> emitter) {
    final Set<Serializable> set = new HashSet<>();
    values.forEachRemaining(set::add);
    emitter.emit(NullObject.instance(), set.size());

}