Example usage for java.util.stream Stream forEach

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

Introduction

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

Prototype

void forEach(Consumer<? super T> action);

Source Link

Document

Performs an action for each element of this stream.

Usage

From source file:edu.umd.umiacs.clip.tools.io.AllFiles.java

public static Path write(Path path, Stream<?> lines, Charset cs, OpenOption... options) {
    if (options.length == 0) {
        options = new OpenOption[] { CREATE_NEW };
    }//from  w  w  w.  j  a  va2 s . com
    Objects.requireNonNull(lines);
    CharsetEncoder encoder = cs.newEncoder();
    try {
        OutputStream out = newOutputStream(path, options);
        if (path.toString().endsWith(".gz")) {
            out = new GZIPOutputStream(out);
        } else if (path.toString().endsWith(".bz2")) {
            out = new BZip2CompressorOutputStream(out);
        }
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, encoder), BUFFER_SIZE)) {
            lines.forEach(line -> {
                try {
                    writer.append(line.toString());
                    writer.newLine();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    return path;
}

From source file:com.baeldung.file.FileOperationsTest.java

@Test
public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException {
    String expectedData = "Hello World from fileTest.txt!!!";

    Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());

    StringBuilder data = new StringBuilder();
    Stream<String> lines = Files.lines(path);
    lines.forEach(line -> data.append(line).append("\n"));
    lines.close();//w w w .  jav  a  2  s  .co  m

    Assert.assertEquals(expectedData, data.toString().trim());
}

From source file:com.baeldung.file.FileOperationsManualTest.java

@Test
public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException {
    String expectedData = "Hello World from fileTest.txt!!!";

    Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());

    StringBuilder data = new StringBuilder();
    Stream<String> lines = Files.lines(path);
    lines.forEach(line -> data.append(line).append("\n"));
    lines.close();//from   w ww.j  a v a  2s.  c  om

    assertEquals(expectedData, data.toString().trim());
}

From source file:enumj.EnumeratorTimingTestBase.java

private Stream<E> testStreamConsumption(Stream<E> stream) {
    stream.forEach(this::consumeStream);
    return stream;
}

From source file:hydrograph.ui.propertywindow.widgets.customwidgets.RadioButtonsWidget.java

@Override
public void attachToPropertySubGroup(AbstractELTContainerWidget container) {
    ELTDefaultSubgroupComposite defaultSubgroupComposite = new ELTDefaultSubgroupComposite(
            container.getContainerControl());
    buttonText = radioButtonConfig.getWidgetDisplayNames();
    buttons = new Button[buttonText.length];
    defaultSubgroupComposite.createContainerWidget();
    defaultSubgroupComposite.numberOfBasicWidgets(buttonText.length + 1);

    AbstractELTWidget defaultLabel = new ELTDefaultLable(radioButtonConfig.getPropertyName());
    defaultSubgroupComposite.attachWidget(defaultLabel);

    setPropertyHelpWidget((Control) defaultLabel.getSWTWidgetControl());

    SelectionListener selectionListener = new SelectionAdapter() {
        @Override//from   www . ja  va2s .  c  o  m
        public void widgetSelected(SelectionEvent event) {
            Button button = ((Button) event.widget);

            matchValue.setMatchValue(button.getText());
            matchValue.setRadioButtonSelected(true);
            propertyDialogButtonBar.enableApplyButton(true);
        }
    };

    for (int i = 0; i < buttonText.length; i++) {
        ELTRadioButton eltRadioButton = new ELTRadioButton(buttonText[i]);
        defaultSubgroupComposite.attachWidget(eltRadioButton);
        buttons[i] = ((Button) eltRadioButton.getSWTWidgetControl());
        ((Button) eltRadioButton.getSWTWidgetControl()).addSelectionListener(selectionListener);
    }
    buttons[0].setSelection(true);

    if (!radioButtonConfig.getRadioButtonListners().isEmpty()) {
        Stream<Button> stream = Arrays.stream(buttons);
        stream.forEach(button -> {
            Listners radioListners = radioButtonConfig.getRadioButtonListners().get(0);
            IELTListener listener = radioListners.getListener();
            Listener listnr = listener.getListener(propertyDialogButtonBar, null, button);
            button.addListener(SWT.Selection, listnr);
        });
    }
    populateWidget();
}

From source file:org.fineract.module.stellar.service.UnprocessedEventObserver.java

@Scheduled(fixedRate = 300000) //Once every five minutes.
void resendUnprocessedMifosPayments() {
    logger.info("Checking for and resending unprocessed payment events.");
    final Stream<FineractPaymentEventPersistency> events = this.fineractPaymentEventRepository
            .findByProcessedFalseAndOutstandingRetriesGreaterThan(0);

    events.forEach(event -> {
        final PaymentPersistency payment = gson.fromJson(event.getPayload(), PaymentPersistency.class);
        this.applicationEventPublisher.publishEvent(new FineractPaymentEvent(this, event.getId(), payment));
    });//from  w w w .j  av  a2  s  .  c  o  m
}

From source file:downloadwebpages.DownloadWebpages.java

/**
 * read the webpages in the text file and save them in the java list
 *//* w w w.j  a  v  a2  s.c o m*/
private void getWebpagesFromFile() {
    try {
        System.out.println("Reading: " + webpagesTxtFilePath);
        webpages = new ArrayList<>(); // initialize list

        Stream<String> stream = Files.lines(Paths.get(webpagesTxtFilePath), Charset.defaultCharset());
        stream.forEach((line) -> {
            System.out.println("Read line: " + line);
            String[] split = line.split("\\t");
            if (split.length > 1) {
                webpages.add(new Pair(split[0], split[1]));
            }
        });
        //stream.forEach(System.out::println); // print line from file
    } catch (IOException ex) {
        Logger.getLogger(DownloadWebpages.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.thoughtworks.go.javasysmon.wrapper.Java9CompatibleCurrentProcess.java

@Override
public void infanticide() {
    LOG.debug("Using java 9 compatible infanticide");
    try {/*from  w  w w  .j ava 2 s .c  o  m*/
        MethodUtils.invokeMethod(currentProcess(), "descendants");
        Stream<Object> processHandles = (Stream<Object>) MethodUtils.invokeMethod(currentProcess(),
                "descendants");
        processHandles.forEach(processHandle -> {
            ProcessHandleReflectionDelegate ph = new ProcessHandleReflectionDelegate(processHandle);
            LOG.debug("Attempting to destroy process {}", ph);
            if (ph.isAlive()) {
                ph.destroy();
                LOG.debug("Destroyed process {}", ph);
            }
        });
    } catch (Exception e) {
        LOG.error("Unable to infanticide", e);
    }
}

From source file:org.fineract.module.stellar.service.UnprocessedEventObserver.java

@Scheduled(fixedRate = 300000) //Once every five minutes.
void resendUnprocessedStellarAdjustments() {
    logger.info("Checking for and resending unprocessed adjustments.");
    final Stream<StellarAdjustOfferEventPersistency> events = this.stellarAdjustOfferEventRepository
            .findByProcessedFalseAndOutstandingRetriesGreaterThan(0);

    events.forEach(event -> {
        final StellarAdjustOfferEvent adjustOfferEvent = new StellarAdjustOfferEvent(this, event.getId(),
                event.getMifosTenantId(), event.getAssetCode());

        this.applicationEventPublisher.publishEvent(adjustOfferEvent);
    });//from w w  w .  j  a va 2 s .  c  o  m
}

From source file:ru.jts_dev.gameserver.service.BroadcastService.java

public final void sendToAll(final OutgoingMessageWrapper message) {
    Stream<GameSession> stream = sessionService.getSessions().size() > THRESHOLD
            ? sessionService.getSessions().values().parallelStream()
            : sessionService.getSessions().values().stream();
    stream.forEach(gameSession -> send(gameSession.getConnectionId(), message));
}