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

The following examples show how to use java.util.stream.Stream#forEachOrdered() . 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 File: StringWithMacrosTypeCoercer.java    From buck with Apache License 2.0 6 votes vote down vote up
/** 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 2
Source File: FileView.java    From mdw with 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 3
Source File: FileView.java    From mdw with 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 4
Source File: JShellTool.java    From openjdk-jdk9 with GNU General Public License v2.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 5
Source File: JShellTool.java    From openjdk-jdk9 with GNU General Public License v2.0 6 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(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 6
Source File: JShellTool.java    From netbeans with 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 7
Source File: TryJShellTool.java    From try-artifact with GNU General Public License v2.0 6 votes vote down vote up
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 8
Source File: AggregatingSanitizer.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
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 9
Source File: ExportUtils.java    From alf.io with 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 10
Source File: SegmentBenchmark.java    From indexr with 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 11
Source File: BEncoder.java    From bt with 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 12
Source File: DataTypes.java    From hkt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static <A> IO<Unit> sequenceStream_(Stream<IO<A>> ios) {
    return () -> {
        try {
            ios.forEachOrdered(IO::runUnchecked);
        }
        catch (UncheckedIOException e) {
            throw e.getCause();
        }
        return unit;
    };
}
 
Example 13
Source File: JShellTool.java    From openjdk-jdk9 with GNU General Public License v2.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
                ? feedback.truncateVarValue(state.varValue(vk))
                : getResourceString("jshell.msg.vars.not.active");
        hard("  %s %s = %s", vk.typeName(), vk.name(), val);
    });
    return true;
}
 
Example 14
Source File: ClientFacade.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 15
Source File: JShellTool.java    From netbeans with 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 16
Source File: JShellTool.java    From netbeans with 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 17
Source File: JsonBuilder.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
public static ArrayNode jsnA(Stream<? extends JsonNode> contents) {
  ArrayNode result = factory.arrayNode();
  contents.forEachOrdered(result::add);
  return result;
}
 
Example 18
Source File: Streams.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
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 19
Source File: Rollup.java    From notification with 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 File: TextFileCheckerTest.java    From keycloak with 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);
}