Example usage for java.util.stream Stream flatMap

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

Introduction

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

Prototype

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);

Source Link

Document

Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

Usage

From source file:com.wrmsr.kleist.util.Itertools.java

public static <T> Stream<T> flatten(Stream<Stream<T>> stream) {
    return stream.flatMap(identity());
}

From source file:com.wrmsr.wava.basic.Basics.java

public static SetMultimap<Name, Name> getBasicInputs(Stream<Basic> basics) {
    return basics.flatMap(b -> b.getAllTargets().stream().map(t -> ImmutablePair.of(t, b.getName())))
            .collect(toHashMultimap());/*from w ww  .  ja  v  a  2  s  .  c o  m*/
}

From source file:me.rojo8399.placeholderapi.impl.utils.TypeUtils.java

public static <T> Stream<? extends T> unmapOptional(Stream<Optional<? extends T>> stream) {
    return stream.flatMap(unmapOptional());
}

From source file:io.github.carlomicieli.footballdb.starter.pages.TableBuilder.java

public TableBuilder row(Stream<Cell> cells) {
    row(cells.flatMap(Cell::values).toArray(String[]::new));
    return this;
}

From source file:io.github.carlomicieli.footballdb.starter.pages.TableBuilder.java

public TableBuilder headers(Stream<Cell> cells) {
    headers(cells.flatMap(Cell::values).toArray(String[]::new));
    return this;
}

From source file:io.syndesis.rest.v1.handler.credential.CredentialHandler.java

@GET
@Path("/callback")
public Response callback(@Context final HttpServletRequest request,
        @Context final HttpServletResponse response) {
    // user could have tried multiple times in parallel or encoutered an
    // error, and that leads to multiple `cred-` cookies being present
    final Set<CredentialFlowState> allStatesFromRequest;
    try {//from  w  w  w  .  ja v  a2s . c om
        allStatesFromRequest = CredentialFlowState.Builder.restoreFrom(state::restoreFrom, request);
    } catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") final RuntimeException e) {
        LOG.debug("Unable to restore credential flow state from request", e);
        return fail(request, response, "Unable to restore the state of authorization");
    }

    if (allStatesFromRequest.isEmpty()) {
        return fail(request, response,
                "Unable to recall the state of authorization, called callback without initiating OAuth autorization?");
    }

    // as a fallback pick the newest one
    final CredentialFlowState newestState = allStatesFromRequest.iterator().next();
    final String providerId = newestState.getProviderId();
    final URI returnUrl = newestState.getReturnUrl();

    final Optional<CredentialFlowState> maybeUpdatedFlowState;
    try {
        final Stream<CredentialFlowState> updatedStatesFromRequest = allStatesFromRequest.stream()
                .map(s -> s.updateFrom(request));

        // let's try to finish with any remaining flow states, as there
        // might be
        // many try with each one
        maybeUpdatedFlowState = updatedStatesFromRequest.flatMap(s -> tryToFinishAcquisition(request, s))
                .findFirst();
    } catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") final RuntimeException e) {
        LOG.debug("Unable to update credential flow state from request", e);
        return fail(request, response, returnUrl, providerId, "Unable to update the state of authorization");
    }

    if (!maybeUpdatedFlowState.isPresent()) {
        return fail(request, response, returnUrl, providerId,
                "Unable to finish authorization, OAuth authorization timed out?");
    }

    final CredentialFlowState flowState = maybeUpdatedFlowState.get();

    final URI successfullReturnUrl = addFragmentTo(flowState.getReturnUrl(),
            success(flowState.getProviderId(), "Successfully authorized Syndesis's access"));

    return Response.temporaryRedirect(successfullReturnUrl)
            .cookie(state.persist(flowState.persistenceKey(), "/", flowState)).build();
}

From source file:com.ikanow.aleph2.graph.titan.services.SimpleGraphDecompService.java

@Override
public void onObjectBatch(Stream<Tuple2<Long, IBatchRecord>> batch, Optional<Integer> batch_size,
        Optional<JsonNode> grouping_key) {

    final HashSet<ObjectNode> mutable_dedup_set = new HashSet<>();

    batch.forEach(t2 -> {/*from w  w  w  . j  a  v a 2s  . co  m*/
        Optionals.ofNullable(_config.get().elements()).forEach(el -> {
            final ObjectNode d_o = (ObjectNode) t2._2().getJson();
            final Stream<JsonNode> froms = Optionals.ofNullable(el.from_fields()).stream()
                    .<JsonNode>map(s -> d_o.get(s)).filter(j -> null != j);
            final Streamable<JsonNode> tos = Streamable.of(Optionals.ofNullable(el.to_fields()))
                    .<JsonNode>map(s -> d_o.get(s)).filter(j -> null != j);

            //TODO (ALEPH-15): hmm need at least some properties here....

            froms.flatMap(from -> tos.<Tuple2<JsonNode, JsonNode>>map(to -> Tuples._2T(from, to)).stream())
                    .forEach(from_to -> {

                        final JsonNode from = from_to._1();
                        final JsonNode to = from_to._2();

                        final ObjectNode mutable_from_key = _mapper.createObjectNode();
                        mutable_from_key.set(GraphAnnotationBean.name, from);
                        mutable_from_key.put(GraphAnnotationBean.type, el.from_type());
                        final ObjectNode mutable_to_key = _mapper.createObjectNode();
                        mutable_to_key.set(GraphAnnotationBean.name, to);
                        mutable_to_key.put(GraphAnnotationBean.type, el.to_type());

                        if (mutable_dedup_set.add(mutable_from_key)) {
                            final ObjectNode mutable_from_vertex = _mapper.createObjectNode();
                            mutable_from_vertex.put(GraphAnnotationBean.type,
                                    GraphAnnotationBean.ElementType.vertex.toString());
                            mutable_from_vertex.set(GraphAnnotationBean.id, mutable_from_key);
                            mutable_from_vertex.put(GraphAnnotationBean.label, from.asText());
                            mutable_from_vertex.set(GraphAnnotationBean.properties,
                                    mutable_from_key.deepCopy());
                            _context.get().emitImmutableObject(_context.get().getNextUnusedId(),
                                    mutable_from_vertex, Optional.empty(), Optional.empty(), Optional.empty());
                        }

                        if (mutable_dedup_set.add(mutable_to_key)) {
                            final ObjectNode mutable_to_vertex = _mapper.createObjectNode();
                            mutable_to_vertex.put(GraphAnnotationBean.type,
                                    GraphAnnotationBean.ElementType.vertex.toString());
                            mutable_to_vertex.set(GraphAnnotationBean.id, mutable_to_key);
                            mutable_to_vertex.put(GraphAnnotationBean.label, to.asText());
                            mutable_to_vertex.set(GraphAnnotationBean.properties, mutable_to_key.deepCopy());
                            _context.get().emitImmutableObject(_context.get().getNextUnusedId(),
                                    mutable_to_vertex, Optional.empty(), Optional.empty(), Optional.empty());
                        }

                        final ObjectNode mutable_edge = _mapper.createObjectNode();
                        mutable_edge.put(GraphAnnotationBean.type,
                                GraphAnnotationBean.ElementType.edge.toString());
                        mutable_edge.put(GraphAnnotationBean.label, el.edge_name());
                        mutable_edge.set(GraphAnnotationBean.outV, mutable_from_key);
                        mutable_edge.set(GraphAnnotationBean.inV, mutable_to_key);
                        _context.get().emitImmutableObject(_context.get().getNextUnusedId(), mutable_edge,
                                Optional.empty(), Optional.empty(), Optional.empty());
                    });
        });
    });
}

From source file:grakn.core.console.ConsoleSession.java

private void executeQuery(String queryString, boolean catchRuntimeException) throws IOException {
    // We'll use streams so we can print the answer out much faster and smoother
    try {// w w  w .j a  v  a 2  s  .  co m
        // Parse the string to get a stream of Graql Queries
        Stream<GraqlQuery> queries = Graql.parseList(queryString);

        // Get the stream of answers for each query (query.stream())
        // Get the  stream of printed answers (printer.toStream(..))
        // Combine the stream of printed answers into one stream (queries.flatMap(..))
        Stream<String> answers = queries.flatMap(query -> printer.toStream(tx.stream(query, infer)));

        // For each printed answer, print them on one line
        answers.forEach(answer -> {
            try {
                consoleReader.println(answer);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    } catch (RuntimeException e) {
        // Flush out all answers from previous iterators in the stream
        consoleReader.flush();

        if (catchRuntimeException) {
            if (!e.getMessage().isEmpty()) {
                printErr.println("Error: " + e.getMessage());
            } else {
                printErr.println("Error: " + e.getClass().getName());
            }
            printErr.println("All uncommitted data is cleared");
            //If console session was terminated by shutdown hook thread, do not try to reopen transaction
            if (terminated.get())
                return;
            reopenTransaction();
        } else {
            throw e;
        }
    }

    consoleReader.flush(); // Flush the ConsoleReader before the next command

    // It is important that we DO NOT close the transaction at the end of a query
    // The user may want to do consecutive operations onto the database
    // The transaction will only close once the user decides to COMMIT or ROLLBACK
}

From source file:alfio.manager.TicketReservationManager.java

private static TotalPrice totalReservationCostWithVAT(PromoCodeDiscount promoCodeDiscount, Event event,
        PriceContainer.VatStatus reservationVatStatus, List<Ticket> tickets,
        Stream<Pair<AdditionalService, List<AdditionalServiceItem>>> additionalServiceItems) {

    List<TicketPriceContainer> ticketPrices = tickets.stream()
            .map(t -> TicketPriceContainer.from(t, reservationVatStatus, event, promoCodeDiscount))
            .collect(toList());//from www  .ja v  a  2  s.c  om
    BigDecimal totalVAT = ticketPrices.stream().map(TicketPriceContainer::getVAT).reduce(BigDecimal.ZERO,
            BigDecimal::add);
    BigDecimal totalDiscount = ticketPrices.stream().map(TicketPriceContainer::getAppliedDiscount)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
    BigDecimal totalNET = ticketPrices.stream().map(TicketPriceContainer::getFinalPrice).reduce(BigDecimal.ZERO,
            BigDecimal::add);
    int discountedTickets = (int) ticketPrices.stream()
            .filter(t -> t.getAppliedDiscount().compareTo(BigDecimal.ZERO) > 0).count();
    int discountAppliedCount = discountedTickets <= 1
            || promoCodeDiscount.getDiscountType() == DiscountType.FIXED_AMOUNT ? discountedTickets : 1;

    List<AdditionalServiceItemPriceContainer> asPrices = additionalServiceItems
            .flatMap(generateASIPriceContainers(event, null)).collect(toList());

    BigDecimal asTotalVAT = asPrices.stream().map(AdditionalServiceItemPriceContainer::getVAT)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
    //FIXME discount is not applied to donations, as it wouldn't make sense. Must be implemented for #111
    BigDecimal asTotalNET = asPrices.stream().map(AdditionalServiceItemPriceContainer::getFinalPrice)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
    return new TotalPrice(unitToCents(totalNET.add(asTotalNET)), unitToCents(totalVAT.add(asTotalVAT)),
            -(MonetaryUtil.unitToCents(totalDiscount)), discountAppliedCount);
}

From source file:org.apache.hadoop.hbase.master.assignment.AssignmentManagerUtil.java

static TransitRegionStateProcedure[] createUnassignProceduresForSplitOrMerge(MasterProcedureEnv env,
        Stream<RegionInfo> regions, int regionReplication) throws IOException {
    List<RegionStateNode> regionNodes = regions
            .flatMap(hri -> IntStream.range(0, regionReplication)
                    .mapToObj(i -> RegionReplicaUtil.getRegionInfoForReplica(hri, i)))
            .map(env.getAssignmentManager().getRegionStates()::getOrCreateRegionStateNode)
            .collect(Collectors.toList());
    TransitRegionStateProcedure[] procs = new TransitRegionStateProcedure[regionNodes.size()];
    boolean rollback = true;
    int i = 0;/*from   w ww  .  j a  v a2s  .co m*/
    // hold the lock at once, and then release it in finally. This is important as SCP may jump in
    // if we release the lock in the middle when we want to do rollback, and cause problems.
    lock(regionNodes);
    try {
        for (; i < procs.length; i++) {
            RegionStateNode regionNode = regionNodes.get(i);
            TransitRegionStateProcedure proc = TransitRegionStateProcedure.unassign(env,
                    regionNode.getRegionInfo());
            if (regionNode.getProcedure() != null) {
                throw new HBaseIOException(
                        "The parent region " + regionNode + " is currently in transition, give up");
            }
            regionNode.setProcedure(proc);
            procs[i] = proc;
        }
        // all succeeded, set rollback to false
        rollback = false;
    } finally {
        if (rollback) {
            for (;;) {
                i--;
                if (i < 0) {
                    break;
                }
                RegionStateNode regionNode = regionNodes.get(i);
                regionNode.unsetProcedure(procs[i]);
            }
        }
        unlock(regionNodes);
    }
    return procs;
}