Java Code Examples for java.util.stream.Stream#forEachOrdered()

The following examples show how to use java.util.stream.Stream#forEachOrdered() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: netbeans   File: JShellTool.java    License: Apache License 2.0 6 votes vote down vote up
private boolean cmdList(String arg) {
    if (arg.length() >= 2 && "-history".startsWith(arg)) {
        return cmdHistory();
    }
    Stream<Snippet> stream = argsOptionsToSnippets(state::snippets,
            this::mainActive, arg, "/list");
    if (stream == null) {
        return false;
    }

    // prevent double newline on empty list
    boolean[] hasOutput = new boolean[1];
    stream.forEachOrdered(sn -> {
        if (!hasOutput[0]) {
            cmdout.println();
            hasOutput[0] = true;
        }
        cmdout.printf("%4s : %s\n", sn.id(), sn.source().replace("\n", "\n       "));
    });
    return true;
}
 
Example 2
/** Merges all adjacent string elements. */
private static ImmutableList<Either<String, MacroContainer>> mergeStringParts(
    Stream<Either<String, MacroContainer>> parts) {
  ImmutableList.Builder<Either<String, MacroContainer>> mergedParts = ImmutableList.builder();
  StringBuilder currentStringPart = new StringBuilder();

  parts.forEachOrdered(
      part -> {
        if (part.isLeft()) {
          currentStringPart.append(part.getLeft());
        } else {
          addStringToParts(mergedParts, currentStringPart);
          mergedParts.add(part);
        }
      });

  addStringToParts(mergedParts, currentStringPart);

  return mergedParts.build();
}
 
Example 3
private boolean cmdList(String arg) {
    if (arg.length() >= 2 && "-history".startsWith(arg)) {
        return cmdHistory();
    }
    Stream<Snippet> stream = argsOptionsToSnippets(state::snippets,
            this::mainActive, arg, "/list");
    if (stream == null) {
        return false;
    }

    // prevent double newline on empty list
    boolean[] hasOutput = new boolean[1];
    stream.forEachOrdered(sn -> {
        if (!hasOutput[0]) {
            cmdout.println();
            hasOutput[0] = true;
        }
        cmdout.printf("%4s : %s\n", sn.id(), sn.source().replace("\n", "\n       "));
    });
    return true;
}
 
Example 4
private boolean cmdMethods(String arg) {
    Stream<MethodSnippet> stream = argsOptionsToSnippets(this::allMethodSnippets,
            this::isActive, arg, "/methods");
    if (stream == null) {
        return false;
    }
    stream.forEachOrdered(meth -> {
        String sig = meth.signature();
        int i = sig.lastIndexOf(")") + 1;
        if (i <= 0) {
            hard("  %s", meth.name());
        } else {
            hard("  %s %s%s", sig.substring(i), meth.name(), sig.substring(0, i));
        }
        printSnippetStatus(meth, true);
    });
    return true;
}
 
Example 5
private boolean cmdList(String arg) {
    if (arg.equals("history")) {
        return cmdHistory();
    }
    Stream<Snippet> stream = argToSnippets(arg, true);
    if (stream == null) {
        // Check if there are any definitions at all
        if (argToSnippets("", false).iterator().hasNext()) {
            hard("No definition or id named %s found.  Try /list without arguments.", arg);
        } else {
            hard("No definition or id named %s found.  There are no active definitions.", arg);
        }
        return false;
    }

    // prevent double newline on empty list
    boolean[] hasOutput = new boolean[1];
    stream.forEachOrdered(sn -> {
        if (!hasOutput[0]) {
            cmdout.println();
            hasOutput[0] = true;
        }
        cmdout.printf("%4s : %s\n", sn.id(), sn.source().replace("\n", "\n       "));
    });
    return true;
}
 
Example 6
Source Project: mdw   File: FileView.java    License: Apache License 2.0 6 votes vote down vote up
private int searchFrom(int startLine, boolean findLast) throws IOException {
    searchIndex = lastIndex = -1;
    try (Stream<String> stream = Files.lines(path)) {
        Stream<String> s = stream.skip(startLine).filter(line -> {
            searchIndex++;
            boolean found = line.toLowerCase().indexOf(search) >= 0;
            if (found && findLast)
                lastIndex = searchIndex + startLine;
            return found;
        });
        if (findLast) {
            s.forEachOrdered(l -> {});
            return lastIndex;
        }
        else {
            return s.findFirst().isPresent() ? searchIndex + startLine : -1;
        }
    }
}
 
Example 7
Source Project: mdw   File: FileView.java    License: Apache License 2.0 6 votes vote down vote up
private int searchTo(int endLine, boolean findLast) throws IOException {
    searchIndex = lastIndex = -1;
    try (Stream<String> stream = Files.lines(path)) {
        Stream<String> s = stream.limit(endLine).filter(line -> {
            searchIndex++;
            boolean found = line.toLowerCase().indexOf(search) >= 0;
            if (found && findLast)
                lastIndex = searchIndex;
            return found;
        });
        if (findLast) {
            s.forEachOrdered(l -> {});
            return lastIndex;
        }
        return s.findFirst().isPresent() ? searchIndex : -1;
    }
}
 
Example 8
Source Project: netbeans   File: JShellTool.java    License: Apache License 2.0 5 votes vote down vote up
private boolean cmdVars(String arg) {
    Stream<VarSnippet> stream = argsOptionsToSnippets(this::allVarSnippets,
            this::isActive, arg, "/vars");
    if (stream == null) {
        return false;
    }
    stream.forEachOrdered(vk ->
    {
        String val = state.status(vk) == Status.VALID
                ? state.varValue(vk)
                : getResourceString("jshell.msg.vars.not.active");
        hard("  %s %s = %s", vk.typeName(), vk.name(), val);
    });
    return true;
}
 
Example 9
Source Project: netbeans   File: JShellTool.java    License: Apache License 2.0 5 votes vote down vote up
private boolean cmdMethods(String arg) {
    Stream<MethodSnippet> stream = argsOptionsToSnippets(this::allMethodSnippets,
            this::isActive, arg, "/methods");
    if (stream == null) {
        return false;
    }
    stream.forEachOrdered(mk
            -> hard("  %s %s", mk.name(), mk.signature())
    );
    return true;
}
 
Example 10
public void processDocumentActions(Stream<DocumentAction> documentActions) {
  LOG.trace("Processing document actions ...");
  BulkProcessor bulkProcessor = bulkProcessorFactory.create(client);
  try {
    documentActions.forEachOrdered(
        documentAction -> {
          DocWriteRequest docWriteRequest = toDocWriteRequest(documentAction);
          bulkProcessor.add(docWriteRequest);
        });
  } finally {
    waitForCompletion(bulkProcessor);
    LOG.debug("Processed document actions.");
  }
}
 
Example 11
private boolean cmdVars(String arg) {
    Stream<VarSnippet> stream = argsOptionsToSnippets(this::allVarSnippets,
            this::isActive, arg, "/vars");
    if (stream == null) {
        return false;
    }
    stream.forEachOrdered(vk ->
    {
        String val = state.status(vk) == Status.VALID
                ? feedback.truncateVarValue(state.varValue(vk))
                : getResourceString("jshell.msg.vars.not.active");
        hard("  %s %s = %s", vk.typeName(), vk.name(), val);
    });
    return true;
}
 
Example 12
private static UnaryOperator<JobDescriptor> applyAll(Stream<UnaryOperator<JobDescriptor>> partialUpdates) {
    return entity -> {
        AtomicReference<JobDescriptor> result = new AtomicReference<>(entity);
        partialUpdates.forEachOrdered(result::updateAndGet);
        return result.get();
    };
}
 
Example 13
static <A> IO<Unit> sequenceStream_(Stream<IO<A>> ios) {
    return () -> {
        try {
            ios.forEachOrdered(IO::runUnchecked);
        }
        catch (UncheckedIOException e) {
            throw e.getCause();
        }
        return unit;
    };
}
 
Example 14
Source Project: bt   File: BEncoder.java    License: Apache License 2.0 5 votes vote down vote up
private void encodeMap(Map<String, Object> map) {
	buf.put((byte) 'd');
	Stream<Entry<String,Object>> str;
	if(map instanceof SortedMap<?, ?> && ((SortedMap<?, ?>) map).comparator() == null)
		str = map.entrySet().stream();
	else
		str = map.entrySet().stream().sorted(Map.Entry.comparingByKey());
	
	str.forEachOrdered(e -> {
		encodeString(e.getKey());
		encodeInternal(e.getValue());
	});
	buf.put((byte) 'e');
}
 
Example 15
Source Project: indexr   File: SegmentBenchmark.java    License: Apache License 2.0 5 votes vote down vote up
@Benchmark
public void travel_stream_forEachOrdered() throws IOException {
    IntegratedSegment.Fd fd = IntegratedSegment.Fd.create("aa", workDir.resolve("integreated"));
    Segment segment = fd.open();
    RowTraversal traversal = segment.rowTraversal();
    Stream<Row> stream = traversal.stream();

    stream.forEachOrdered(new RowTraveler(columnSchemas));
}
 
Example 16
Source Project: alf.io   File: ExportUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void exportCsv(String fileName, String[] header, Stream<String[]> data, HttpServletResponse response) throws IOException {
    response.setContentType("text/csv;charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

    try (ServletOutputStream out = response.getOutputStream(); CSVWriter writer = new CSVWriter(new OutputStreamWriter(out, UTF_8))) {
        for (int marker : ExportUtils.BOM_MARKERS) {
            out.write(marker);
        }
        writer.writeNext(header);
        data.forEachOrdered(writer::writeNext);
        writer.flush();
        out.flush();
    }
}
 
Example 17
public static <T> void forEachWithIndex(Stream<T> stream, IndexedConsumer<T> consumer) {
    final Counter index = new Counter();
    stream.forEachOrdered(t -> consumer.accept(t, index.next()));
}
 
Example 18
public static ArrayNode jsnA(Stream<? extends JsonNode> contents) {
  ArrayNode result = factory.arrayNode();
  contents.forEachOrdered(result::add);
  return result;
}
 
Example 19
Source Project: notification   File: Rollup.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Iterates over the notifications and uses the {@link Rule} and {@link Matcher} objects to roll
 * up the notifications based on the rules.
 *
 * @param notifications Notifications to roll up
 * @return Rolled up notifications
 */
public Stream<Notification> rollup(final Stream<Notification> notifications) {
  Objects.requireNonNull(notifications, "notifications == null");

  if (rules.isEmpty()) {
    return notifications;
  }

  final TreeSet<Notification> rollups = new TreeSet<>();

  notifications.forEachOrdered(
      notification -> {
        final Rule rule = rules.get(notification.getCategory());

        // If the notification category doesn't match any rule categories,
        // add the notification as-is to the list of rollups.
        if (rule == null || !rule.isValid()) {
          rollups.add(notification);
        } else if (matchers.isEmpty()) {
          // If we don't have any matchers yet, add the first one
          matchers.add(new Matcher(rule, notification));
        } else {
          // Loop through the existing matchers to see if this
          // notification falls into any previous rollups
          boolean matched = false;
          for (final Matcher matcher : matchers) {
            if (matcher.test(notification)) {
              matched = true;

              // if the matcher is now full, add it to the rollups and
              // remove it from the available matchers which still
              // have empty space.
              if (matcher.isFull()) {
                matchers.remove(matcher);
                rollups.add(matcher.getNotification());
              }
              break;
            }
          }

          // If the notification didn't match any existing rollups, add it
          // as a new matcher
          if (!matched) {
            matchers.add(new Matcher(rule, notification));
          }
        }
      });

  // Pull out the rolled up notifications out of the matchers
  for (final Matcher match : matchers) {
    rollups.add(match.getNotification());
  }

  return rollups.stream();
}
 
Example 20
Source Project: keycloak   File: TextFileCheckerTest.java    License: Apache License 2.0 4 votes vote down vote up
private Consumer<Stream<String>> collector(Collection<String> target) {
    return (Stream<String> s) -> s.forEachOrdered(target::add);
}