Example usage for java.util Collection iterator

List of usage examples for java.util Collection iterator

Introduction

In this page you can find the example usage for java.util Collection iterator.

Prototype

Iterator<E> iterator();

Source Link

Document

Returns an iterator over the elements in this collection.

Usage

From source file:edu.umn.msi.tropix.proteomics.tools.DTAToMzXML.java

public static void main(final String[] args) throws Exception {
    if (args.length < 1) {
        usage();//from   www.  j  a  v a  2 s. c  om
        System.exit(0);
    }
    Collection<File> files = null;

    if (args[0].equals("-files")) {
        if (args.length < 2) {
            out.println("No files specified.");
            usage();
            exit(-1);
        } else {
            files = new ArrayList<File>(args.length - 1);
            for (int i = 1; i < args.length; i++) {
                files.add(new File(args[i]));
            }
        }
    } else if (args[0].equals("-directory")) {
        File directory;
        if (args.length < 2) {
            directory = new File(System.getProperty("user.dir"));
        } else {
            directory = new File(args[2]);
        }
        files = FileUtilsFactory.getInstance().listFiles(directory, new String[] { "dta" }, false);
    } else {
        usage();
        exit(-1);
    }

    final InMemoryDTAListImpl dtaList = new InMemoryDTAListImpl();
    File firstFile = null;
    if (files.size() == 0) {
        out.println("No files found.");
        exit(-1);
    } else {
        firstFile = files.iterator().next();
    }
    for (final File file : files) {
        dtaList.add(FileUtils.readFileToByteArray(file), file.getName());
    }

    final DTAToMzXMLConverter dtaToMzXMLConverter = new DTAToMzXMLConverterImpl();
    final MzXML mzxml = dtaToMzXMLConverter.dtaToMzXML(dtaList, null);
    final String mzxmlName = firstFile.getName().substring(0, firstFile.getName().indexOf(".")) + ".mzXML";
    new MzXMLUtility().serialize(mzxml, mzxmlName);
}

From source file:edu.hawaii.soest.hioos.storx.StorXDispatcher.java

/**
 * The main method for running the code @ param args[] the command line list
 * of string arguments, none are needed//from  w  ww  .j a v a2 s .c o m
 */
public static void main(String args[]) {

    try {
        // create a new instance of the StorXDispatcher object, and parse
        // the command
        // line arguments as settings for this instance
        final StorXDispatcher storXDispatcher = new StorXDispatcher();

        // Handle ctrl-c's and other abrupt death signals to the process
        Runtime.getRuntime().addShutdownHook(new Thread() {
            // stop the streaming process
            public void run() {
                Collection sourceCollection = storXDispatcher.sourceMap.values();
                for (Iterator iterator = sourceCollection.iterator(); iterator.hasNext();) {

                    Object sourceObject = iterator.next();

                    try {

                        // disconnect StorX sources
                        StorXSource source = (StorXSource) sourceObject;
                        logger.info("Disconnecting source: " + source.getRBNBClientName());
                        source.stopConnection();

                    } catch (java.lang.ClassCastException cce) {

                        // disconnect ISUS sources
                        try {
                            ISUSSource source = (ISUSSource) sourceObject;
                            logger.info("Disconnecting source: " + source.getRBNBClientName());
                            source.stopConnection();

                        } catch (java.lang.ClassCastException cce2) {

                            // disconnect CTD sources
                            CTDSource source = (CTDSource) sourceObject;
                            logger.info("Disconnecting source: " + source.getRBNBClientName());
                            source.stopConnection();

                        } // end try/catch

                    } // end try/catch

                } // end for()

            } // end run()

        } // end new Thread()

        ); // end addShutDownHook()

        // parse the commandline arguments to configure the connection, then
        // start the streaming connection between the source and the RBNB
        // server.
        if (storXDispatcher.parseArgs(args) && storXDispatcher.parseConfiguration()) {

            // establish the individual source connections with the RBNB
            if (storXDispatcher.connect()) {

                // fetch data on a schedule
                TimerTask fetchData = new TimerTask() {
                    public void run() {
                        logger.debug("TimerTask.run() called.");
                        storXDispatcher.execute();
                    }
                };

                Timer executeTimer = new Timer("Execute Timer");
                // run the fetchData timer task at the default interval
                executeTimer.scheduleAtFixedRate(fetchData, new Date(), storXDispatcher.executeInterval);

            } else {
                logger.info("Could not establish a connection to the DataTurbine. Exiting.");
                System.exit(0);
            }

        }

    } catch (Exception e) {
        logger.info("Error in main(): " + e.getMessage());
        e.printStackTrace();

    }
}

From source file:facade.examples.Collections.java

/**
 * Run the examples// w w  w  . j  av a 2 s .co  m
 * @param args <i>ignored</i>
 */
public static void main(String[] args) {

    /* RESISTORS IN PARALLEL WITH FACADE */

    System.out.println("-> With facade: ");
    /* Empty collection of resistors */
    Collection<Double> resistors = new ArrayList<Double>();
    /* adding values. on() modifies the collection in place */
    on(resistors).add(1.5, 3.0, 15.0, 30.0, 150.0);
    /* computing resistance. with() works on a collection copy. */
    double r = 1.0 / with(resistors).map(inverse).reduce(sum);
    /* pretty printing the resistors */
    System.out.println("[ " + with(resistors).join(", ") + " ]");
    /* printing the equivalent resistor */
    System.out.println(r);

    /* --------------------------------------------------------------- */
    System.out.println();
    /* --------------------------------------------------------------- */

    /* RESISTORS IN PARALLEL WITH CLASSIC JAVA */

    System.out.println("-> Without facade: ");
    /* Empty collection of resistors */
    resistors = new ArrayList<Double>();
    /* adding values */
    resistors.add(1.5);
    resistors.add(3.0);
    resistors.add(15.0);
    resistors.add(30.0);
    resistors.add(150.0);
    /* computing resistance */
    double sum = 0.0;
    for (Double resistor : resistors) {
        sum += 1.0 / resistor;
    }
    r = 1.0 / sum;
    /* pretty printing the resistors */
    StringBuilder sb = new StringBuilder();
    sb.append("[ ");
    Iterator<Double> it = resistors.iterator();
    if (it.hasNext()) {
        sb.append(it.next());
    }
    while (it.hasNext()) {
        sb.append(", ").append(it.next());
    }
    sb.append(" ]");
    System.out.println(sb.toString());
    /* printing the equivalent resistor */
    System.out.println(r);

}

From source file:it.unimi.di.big.mg4j.tool.URLMPHVirtualDocumentResolver.java

public static void main(final String[] arg) throws JSAPException, IOException {
    final SimpleJSAP jsap = new SimpleJSAP(URLMPHVirtualDocumentResolver.class.getName(),
            "Builds a URL document resolver from a sequence of URIs, extracted typically using ScanMetadata, using a suitable function. You can specify that the list is sorted, in which case it is possible to generate a resolver that occupies less space.",
            new Parameter[] {
                    new Switch("sorted", 's', "sorted",
                            "URIs are sorted: use a monotone minimal perfect hash function."),
                    new Switch("iso", 'i', "iso",
                            "Use ISO-8859-1 coding internally (i.e., just use the lower eight bits of each character)."),
                    new FlaggedOption("bufferSize", JSAP.INTSIZE_PARSER, "64Ki", JSAP.NOT_REQUIRED, 'b',
                            "buffer-size", "The size of the I/O buffer used to read terms."),
                    new FlaggedOption("class", MG4JClassParser.getParser(), JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED,
                            'c', "class",
                            "A class used to create the function from URIs to their ranks; defaults to it.unimi.dsi.sux4j.mph.MHWCFunction for non-sorted inputs, and to it.unimi.dsi.sux4j.mph.TwoStepsLcpMonotoneMinimalPerfectHashFunction for sorted inputs."),
                    new FlaggedOption("width", JSAP.INTEGER_PARSER, Integer.toString(Long.SIZE),
                            JSAP.NOT_REQUIRED, 'w', "width",
                            "The width, in bits, of the signatures used to sign the function from URIs to their rank."),
                    new FlaggedOption("termFile", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'o',
                            "offline",
                            "Read terms from this file (without loading them into core memory) instead of standard input."),
                    new FlaggedOption("uniqueUris", JSAP.INTSIZE_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED,
                            'U', "unique-uris",
                            "Force URIs to be unique by adding random garbage at the end of duplicates; the argument is an upper bound for the number of URIs that will be read, and will be used to create a Bloom filter."),
                    new UnflaggedOption("resolver", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED,
                            JSAP.NOT_GREEDY, "The filename for the resolver.") });

    JSAPResult jsapResult = jsap.parse(arg);
    if (jsap.messagePrinted())
        return;//from w  w  w  . j av a 2s. c o m

    final int bufferSize = jsapResult.getInt("bufferSize");
    final String resolverName = jsapResult.getString("resolver");
    //final Class<?> tableClass = jsapResult.getClass( "class" );
    final boolean iso = jsapResult.getBoolean("iso");
    String termFile = jsapResult.getString("termFile");

    BloomFilter<Void> filter = null;
    final boolean uniqueURIs = jsapResult.userSpecified("uniqueUris");
    if (uniqueURIs)
        filter = BloomFilter.create(jsapResult.getInt("uniqueUris"));

    final Collection<? extends CharSequence> collection;
    if (termFile == null) {
        ArrayList<MutableString> termList = new ArrayList<MutableString>();
        final ProgressLogger pl = new ProgressLogger();
        pl.itemsName = "URIs";
        final LineIterator termIterator = new LineIterator(
                new FastBufferedReader(new InputStreamReader(System.in, "UTF-8"), bufferSize), pl);

        pl.start("Reading URIs...");
        MutableString uri;
        while (termIterator.hasNext()) {
            uri = termIterator.next();
            if (uniqueURIs)
                makeUnique(filter, uri);
            termList.add(uri.copy());
        }
        pl.done();

        collection = termList;
    } else {
        if (uniqueURIs) {
            // Create temporary file with unique URIs
            final ProgressLogger pl = new ProgressLogger();
            pl.itemsName = "URIs";
            pl.start("Copying URIs...");
            final LineIterator termIterator = new LineIterator(
                    new FastBufferedReader(new InputStreamReader(new FileInputStream(termFile)), bufferSize),
                    pl);
            File temp = File.createTempFile(URLMPHVirtualDocumentResolver.class.getName(), ".uniqueuris");
            temp.deleteOnExit();
            termFile = temp.toString();
            final FastBufferedOutputStream outputStream = new FastBufferedOutputStream(
                    new FileOutputStream(termFile), bufferSize);
            MutableString uri;
            while (termIterator.hasNext()) {
                uri = termIterator.next();
                makeUnique(filter, uri);
                uri.writeUTF8(outputStream);
                outputStream.write('\n');
            }
            pl.done();
            outputStream.close();
        }
        collection = new FileLinesCollection(termFile, "UTF-8");
    }
    LOGGER.debug("Building function...");
    final int width = jsapResult.getInt("width");
    if (jsapResult.getBoolean("sorted"))
        BinIO.storeObject(
                new URLMPHVirtualDocumentResolver(
                        new ShiftAddXorSignedStringMap(collection.iterator(),
                                new TwoStepsLcpMonotoneMinimalPerfectHashFunction<CharSequence>(collection,
                                        iso ? TransformationStrategies.prefixFreeIso()
                                                : TransformationStrategies.prefixFreeUtf16()),
                                width)),
                resolverName);
    else
        BinIO.storeObject(
                new URLMPHVirtualDocumentResolver(new ShiftAddXorSignedStringMap(collection.iterator(),
                        new MWHCFunction<CharSequence>(collection,
                                iso ? TransformationStrategies.iso() : TransformationStrategies.utf16()),
                        width)),
                resolverName);
    LOGGER.debug(" done.");
}

From source file:Main.java

public static <T> T first(Collection<T> c) {
    return (T) c.iterator().next();
}

From source file:Main.java

public static Object firstFrom(Collection collection) {
    return collection.iterator().next();
}

From source file:Main.java

public static <T> T carelessGetFirst(Collection<T> list) {
    return list != null && list.iterator().hasNext() ? list.iterator().next() : null;
}

From source file:Main.java

public static Object firstOrElse(Collection l, Object alt) {
    Iterator i = l.iterator();
    if (i.hasNext())
        return i.next();
    return alt;//w  w w  . j  a v  a 2s  .c om
}

From source file:Main.java

public static <T> void cleanNulls(Collection<T> c) {
    Iterator<T> it = c.iterator();
    try {/*w  ww. j  ava2  s  .c  om*/
        while (it.hasNext())
            if (it.next() == null)
                c.remove(null);
    } catch (NullPointerException e) {
        // Does not permit nulls, it should be ok
    }
}

From source file:Main.java

public static void display(Collection collection) {
    Iterator iterator = collection.iterator();
    while (iterator.hasNext()) {
        System.out.print(iterator.next() + " ");
    }/*from   w  w w .  j  a v  a 2s  .  c  o m*/
    System.out.println();
}