Example usage for java.util.stream Stream iterator

List of usage examples for java.util.stream Stream iterator

Introduction

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

Prototype

Iterator<T> iterator();

Source Link

Document

Returns an iterator for the elements of this stream.

Usage

From source file:listfiles.ListFiles.java

/**
 * @param args the command line arguments
 */// w ww.  jav  a 2 s. c  om
public static void main(String[] args) {
    // TODO code application logic here
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String folderPath = "";
    String fileName = "DirectoryFiles.xlsx";

    try {
        System.out.println("Folder path :");
        folderPath = reader.readLine();
        //System.out.println("Output File Name :");
        //fileName = reader.readLine();

        XSSFWorkbook wb = new XSSFWorkbook();
        FileOutputStream fileOut = new FileOutputStream(folderPath + "\\" + fileName);
        XSSFSheet sheet1 = wb.createSheet("Files");
        int row = 0;
        Stream<Path> stream = Files.walk(Paths.get(folderPath));
        Iterator<Path> pathIt = stream.iterator();
        String ext = "";

        while (pathIt.hasNext()) {
            Path filePath = pathIt.next();
            Cell cell1 = checkRowCellExists(sheet1, row, 0);
            Cell cell2 = checkRowCellExists(sheet1, row, 1);
            row++;
            ext = FilenameUtils.getExtension(filePath.getFileName().toString());
            cell1.setCellValue(filePath.getFileName().toString());
            cell2.setCellValue(ext);

        }
        sheet1.autoSizeColumn(0);
        sheet1.autoSizeColumn(1);

        wb.write(fileOut);
        fileOut.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("Program Finished");
}

From source file:Main.java

public static <A, B, C> Stream<C> zip(Stream<A> as, Stream<B> bs, BiFunction<A, B, C> f) {
    Iterator<A> asIterator = as.iterator();
    Iterator<B> bsIterator = bs.iterator();

    Builder<C> builder = Stream.builder();

    while (asIterator.hasNext() && bsIterator.hasNext()) {
        builder.add(f.apply(asIterator.next(), bsIterator.next()));
    }/*from  w w w. j  a  v  a 2 s.co  m*/

    return builder.build();
}

From source file:Main.java

/**
 * Zips the specified stream with its indices.
 *//*www  . ja  v  a  2  s. c  om*/
public static <T> Stream<Map.Entry<Integer, T>> zipWithIndex(Stream<? extends T> stream, int startIndex) {
    return iterate(new Iterator<Map.Entry<Integer, T>>() {
        private final Iterator<? extends T> streamIterator = stream.iterator();
        private int index = startIndex;

        @Override
        public boolean hasNext() {
            return streamIterator.hasNext();
        }

        @Override
        public Map.Entry<Integer, T> next() {
            return new AbstractMap.SimpleImmutableEntry<>(index++, streamIterator.next());
        }
    });
}

From source file:com.uber.hoodie.common.model.HoodieTestUtils.java

public static void assertStreamEquals(String message, Stream<?> expected, Stream<?> actual) {
    Iterator<?> iter1 = expected.iterator();
    Iterator<?> iter2 = actual.iterator();
    while (iter1.hasNext() && iter2.hasNext()) {
        assertEquals(message, iter1.next(), iter2.next());
    }//from ww  w . java  2  s.c om
    assert !iter1.hasNext() && !iter2.hasNext();
}

From source file:com.willwinder.universalgcodesender.utils.FirmwareUtils.java

/**
 * Copy any missing files from the the jar's resources/firmware_config/ dir
 * into the settings/firmware_config dir.
 *///from  w w  w  .  j  a  va 2 s  .  co m
public synchronized static void initialize() {
    System.out.println("Initializing firmware... ...");
    File firmwareConfig = new File(SettingsFactory.getSettingsDirectory(), FIRMWARE_CONFIG_DIRNAME);

    // Create directory if it's missing.
    if (!firmwareConfig.exists()) {
        firmwareConfig.mkdirs();
    }

    FileSystem fileSystem = null;

    // Copy firmware config files.
    try {
        final String dir = "/resources/firmware_config/";

        URI location = FirmwareUtils.class.getResource(dir).toURI();

        Path myPath;
        if (location.getScheme().equals("jar")) {
            try {
                // In case the filesystem already exists.
                fileSystem = FileSystems.getFileSystem(location);
            } catch (FileSystemNotFoundException e) {
                // Otherwise create the new filesystem.
                fileSystem = FileSystems.newFileSystem(location, Collections.<String, String>emptyMap());
            }

            myPath = fileSystem.getPath(dir);
        } else {
            myPath = Paths.get(location);
        }

        Stream<Path> files = Files.walk(myPath, 1);
        for (Path path : (Iterable<Path>) () -> files.iterator()) {
            System.out.println(path);
            final String name = path.getFileName().toString();
            File fwConfig = new File(firmwareConfig, name);
            if (name.endsWith(".json")) {
                boolean copyFile = !fwConfig.exists();
                ControllerSettings jarSetting = getSettingsForStream(Files.newInputStream(path));

                // If the file is outdated... ask the user (once).
                if (fwConfig.exists()) {
                    ControllerSettings current = getSettingsForStream(new FileInputStream(fwConfig));
                    boolean outOfDate = current.getVersion() < jarSetting.getVersion();
                    if (outOfDate && !userNotified && !overwriteOldFiles) {
                        int result = NarrowOptionPane.showNarrowConfirmDialog(200,
                                Localization.getString("settings.file.outOfDate.message"),
                                Localization.getString("settings.file.outOfDate.title"),
                                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        overwriteOldFiles = result == JOptionPane.OK_OPTION;
                        userNotified = true;
                    }

                    if (overwriteOldFiles) {
                        copyFile = true;
                        jarSetting.getProcessorConfigs().Custom = current.getProcessorConfigs().Custom;
                    }
                }

                // Copy file from jar to firmware_config directory.
                if (copyFile) {
                    try {
                        save(fwConfig, jarSetting);
                    } catch (IOException ex) {
                        logger.log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    } catch (Exception ex) {
        String errorMessage = String.format("%s %s", Localization.getString("settings.file.generalError"),
                ex.getLocalizedMessage());
        GUIHelpers.displayErrorDialog(errorMessage);
        logger.log(Level.SEVERE, errorMessage, ex);
    } finally {
        if (fileSystem != null) {
            try {
                fileSystem.close();
            } catch (IOException ex) {
                logger.log(Level.SEVERE, "Problem closing filesystem.", ex);
            }
        }
    }

    configFiles.clear();
    for (File f : firmwareConfig.listFiles()) {
        try {
            ControllerSettings config = new Gson().fromJson(new FileReader(f), ControllerSettings.class);
            //ConfigLoader config = new ConfigLoader(f);
            configFiles.put(config.getName(), new ConfigTuple(config, f));
        } catch (FileNotFoundException | JsonSyntaxException | JsonIOException ex) {
            GUIHelpers.displayErrorDialog("Unable to load configuration files: " + f.getAbsolutePath());
        }
    }
}

From source file:com.massabot.codesender.utils.FirmwareUtils.java

public synchronized static void initialize() {
    System.out.println("Initializing firmware... ...");
    File firmwareConfig = new File(SettingsFactory.getSettingsDirectory(), FIRMWARE_CONFIG_DIRNAME);

    // Create directory if it's missing.
    if (!firmwareConfig.exists()) {
        firmwareConfig.mkdirs();// w w w  .  j  ava 2s  . c o  m
    }

    FileSystem fileSystem = null;

    // Copy firmware config files.
    try {
        final String dir = "/resources/firmware_config/";

        URI location = FirmwareUtils.class.getResource(dir).toURI();

        Path myPath;
        if (location.getScheme().equals("jar")) {
            try {
                // In case the filesystem already exists.
                fileSystem = FileSystems.getFileSystem(location);
            } catch (FileSystemNotFoundException e) {
                // Otherwise create the new filesystem.
                fileSystem = FileSystems.newFileSystem(location, Collections.<String, String>emptyMap());
            }

            myPath = fileSystem.getPath(dir);
        } else {
            myPath = Paths.get(location);
        }

        Stream<Path> files = Files.walk(myPath, 1);
        for (Path path : (Iterable<Path>) () -> files.iterator()) {
            System.out.println(path);
            final String name = path.getFileName().toString();
            File fwConfig = new File(firmwareConfig, name);
            if (name.endsWith(".json")) {
                boolean copyFile = !fwConfig.exists();
                ControllerSettings jarSetting = getSettingsForStream(Files.newInputStream(path));

                // If the file is outdated... ask the user (once).
                if (fwConfig.exists()) {
                    ControllerSettings current = getSettingsForStream(new FileInputStream(fwConfig));
                    boolean outOfDate = current.getVersion() < jarSetting.getVersion();
                    if (outOfDate && !userNotified && !overwriteOldFiles) {
                        int result = NarrowOptionPane.showNarrowConfirmDialog(200,
                                Localization.getString("settings.file.outOfDate.message"),
                                Localization.getString("settings.file.outOfDate.title"),
                                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        overwriteOldFiles = result == JOptionPane.OK_OPTION;
                        userNotified = true;
                    }

                    if (overwriteOldFiles) {
                        copyFile = true;
                        jarSetting.getProcessorConfigs().Custom = current.getProcessorConfigs().Custom;
                    }
                }

                // Copy file from jar to firmware_config directory.
                if (copyFile) {
                    try {
                        save(fwConfig, jarSetting);
                    } catch (IOException ex) {
                        logger.log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    } catch (Exception ex) {
        String errorMessage = String.format("%s %s", Localization.getString("settings.file.generalError"),
                ex.getLocalizedMessage());
        GUIHelpers.displayErrorDialog(errorMessage);
        logger.log(Level.SEVERE, errorMessage, ex);
    } finally {
        if (fileSystem != null) {
            try {
                fileSystem.close();
            } catch (IOException ex) {
                logger.log(Level.SEVERE, "Problem closing filesystem.", ex);
            }
        }
    }

    configFiles.clear();
    for (File f : firmwareConfig.listFiles()) {
        try {
            ControllerSettings config = new Gson().fromJson(new FileReader(f), ControllerSettings.class);
            // ConfigLoader config = new ConfigLoader(f);
            configFiles.put(config.getName(), new ConfigTuple(config, f));
        } catch (FileNotFoundException | JsonSyntaxException | JsonIOException ex) {
            GUIHelpers.displayErrorDialog("Unable to load configuration files: " + f.getAbsolutePath());
        }
    }
}

From source file:com.ikanow.aleph2.graph.titan.utils.TitanGraphBuildingUtils.java

/** Tidy up duplicates created because of the lack of consistency in deduplication (+lack of upsert!)
 * @param tx//ww  w .j  a  va2  s. co  m
 * @param grouped_vertices
 * @param mutable_stats_per_batch
 */
public static void mergeDuplicates(final TitanTransaction tx, final String bucket_path,
        final Map<JsonNode, List<Vertex>> grouped_vertices, final MutableStatsBean mutable_stats_per_batch) {
    grouped_vertices.entrySet().stream().filter(kv -> !kv.getValue().isEmpty()).forEach(kv -> {

        final Stream<Vertex> vertices = kv.getValue().stream().sorted((a, b) -> postProcSortingMethod(a, b));
        final Iterator<Vertex> it = vertices.iterator();
        if (it.hasNext()) {
            final long matches_found = kv.getValue().size() - 1;
            mutable_stats_per_batch.vertex_matches_found += matches_found; //(#vertices)
            if (matches_found > 0) {
                mutable_stats_per_batch.vertices_updated++;//(#keys)
            }

            final Vertex merge_into = it.next();
            if (it.hasNext()) {
                mutable_stats_per_batch.vertices_updated++;
            }
            it.forEachRemaining(v -> {
                // special case: add all buckets, update times etc
                Optionals.streamOf(v.properties(GraphAnnotationBean.a2_p), false).map(vp -> vp.value())
                        .forEach(val -> merge_into.property(Cardinality.set, GraphAnnotationBean.a2_p, val));
                merge_into.property(GraphAnnotationBean.a2_tm, new Date().getTime());

                // copy vertex properties into the "merge_into" vertex
                Optionals.streamOf(v.properties(), false).filter(vp -> !_RESERVED_PROPERTIES.contains(vp.key())) // (ie don't overwrite system properties)
                        .forEach(vp -> merge_into.property(vp.key(), vp.value()));

                // OK edges are the difficult bit
                mergeEdges(bucket_path, Direction.IN, false, merge_into, v, mutable_stats_per_batch);
                mergeEdges(bucket_path, Direction.OUT, false, merge_into, v, mutable_stats_per_batch);

                // (finally remove this vertex)
                // (previously - commened out code, we just removed the bucket, but since we're trying to remove singletons, we'll always delete)
                //Optionals.streamOf(v.properties(GraphAnnotationBean.a2_p), false).filter(vp -> bucket_path.equals(vp.value())).forEach(vp -> vp.remove());
                //if (!v.properties(GraphAnnotationBean.a2_p).hasNext()) v.remove();
                v.remove();
            });
        }

    });
}

From source file:net.geoprism.localization.LocaleManager.java

private Collection<Locale> loadCLDRs() {
    try {/*ww  w .j  a  v  a2 s  .  c  o  m*/

        // Get the list of known CLDR locale
        Set<Locale> locales = new HashSet<Locale>();

        Set<String> paths = new HashSet<String>();

        URL resource = this.getClass().getResource("/cldr/main");
        URI uri = resource.toURI();

        if (uri.getScheme().equals("jar")) {
            FileSystem fileSystem = FileSystems.newFileSystem(uri, new HashMap<String, Object>());
            Path path = fileSystem.getPath("/cldr/main");

            Stream<Path> walk = Files.walk(path, 1);

            try {
                for (Iterator<Path> it = walk.iterator(); it.hasNext();) {
                    Path location = it.next();

                    paths.add(location.toAbsolutePath().toString());
                }
            } finally {
                walk.close();
            }
        } else {
            String url = resource.getPath();
            File root = new File(url);

            File[] files = root.listFiles(new DirectoryFilter());

            if (files != null) {
                for (File file : files) {
                    paths.add(file.getAbsolutePath());
                }
            }
        }

        for (String path : paths) {
            File file = new File(path);

            String filename = file.getName();

            locales.add(LocaleManager.getLocaleForName(filename));
        }

        return locales;
    } catch (Exception e) {
        throw new ProgrammingErrorException(e);
    }
}

From source file:com.github.tteofili.looseen.Test20NewsgroupsClassification.java

private void delete(Path... paths) throws IOException {
    for (Path path : paths) {
        if (Files.isDirectory(path)) {
            Stream<Path> pathStream = Files.list(path);
            Iterator<Path> iterator = pathStream.iterator();
            while (iterator.hasNext()) {
                Files.delete(iterator.next());
            }/* w w  w.j  ava 2  s .  c o m*/
        }
    }

}

From source file:enumj.Enumerator.java

/**
 * Returns an enumerator enumerating over the elements of an existing
 * {@code Stream}.//from   ww w  .  jav  a2s . c  o m
 * <p>
 * If {@link Stream#isParallel()} returns true on
 * {@code source} then the order of elements is undetermined.
 * </p>
 *
 * @param <E> the type of elements being enumerated.
 * @param source the {@link Stream} being enumerated upon.
 * @return the new enumerator.
 * @exception IllegalArgumentException {@code source} is null.
 */
public static <E> Enumerator<E> of(Stream<E> source) {
    Checks.ensureNotNull(source, Messages.NULL_ENUMERATOR_SOURCE);
    return of(source.iterator());
}