limit ( )源码实例Demo

java.util.stream.Stream#limit ( )源码实例Demo

下面列出了java.util.stream.Stream#limit ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Override
public Stream<Attribute> findAll(Query<Attribute> q) {
  if (currentUserIsSuOrSystem()) {
    return delegate().findAll(q);
  } else {
    Query<Attribute> qWithoutLimitOffset = new QueryImpl<>(q);
    qWithoutLimitOffset.offset(0).pageSize(Integer.MAX_VALUE);
    Stream<Attribute> attrs = delegate().findAll(qWithoutLimitOffset);
    Stream<Attribute> filteredAttrs = filterReadMetadataPermission(attrs);
    if (q.getOffset() > 0) {
      filteredAttrs = filteredAttrs.skip(q.getOffset());
    }
    if (q.getPageSize() > 0) {
      filteredAttrs = filteredAttrs.limit(q.getPageSize());
    }
    return filteredAttrs;
  }
}
 
源代码2 项目: spring-data-keyvalue   文件: SpelQueryEngine.java
private static <S> List<S> filterMatchingRange(List<S> source, @Nullable SpelCriteria criteria, long offset,
		int rows) {

	Stream<S> stream = source.stream();

	if (criteria != null) {
		stream = stream.filter(it -> evaluateExpression(criteria, it));
	}
	if (offset > 0) {
		stream = stream.skip(offset);
	}
	if (rows > 0) {
		stream = stream.limit(rows);
	}

	return stream.collect(Collectors.toList());
}
 
源代码3 项目: rdf2x   文件: RelationExtractor.java
/**
 * Get stream of entity types to based on given strategy, relation row will be created for each one
 *
 * @param instance instance to get types from
 * @return stream of entity types based on given strategy, relation row will be created for each one
 */
private Stream<Integer> getRelationEntityTypes(Instance instance) {
    RelationSchemaStrategy strategy = config.getSchemaStrategy();
    // in default, return all types
    Stream<Integer> types = instance.getTypes().stream();
    if (strategy == Predicates || strategy == SingleTable) {
        // create row for one type only
        types = types.limit(1);
    } else if (config.isRootTypesOnly()) {
        // filter out types that have a superclass to ensure relations are only created between root classes
        if (instance.getTypes().size() > 1) {
            types = types.filter(type -> !classGraph.hasSuperClasses(type));
        }
    }
    return types;
}
 
源代码4 项目: business   文件: BaseInMemoryRepository.java
@Override
public Stream<A> get(Specification<A> specification, Option... options) {
    Stream<A> stream = bucket.values()
            .stream()
            .filter(specification.asPredicate());
    for (Option option : options) {
        if (option instanceof OffsetOption) {
            stream = stream.skip(((OffsetOption) option).getOffset());
        } else if (option instanceof LimitOption) {
            stream = stream.limit(((LimitOption) option).getLimit());
        } else if (option instanceof SortOption) {
            stream = stream.sorted(((SortOption) option).buildComparator());
        }
    }
    return stream;
}
 
源代码5 项目: presto   文件: PrestoResultSet.java
private static <T> Iterator<T> flatten(Iterator<Iterable<T>> iterator, long maxRows)
{
    Stream<T> stream = Streams.stream(iterator)
            .flatMap(Streams::stream);
    if (maxRows > 0) {
        stream = stream.limit(maxRows);
    }
    return stream.iterator();
}
 
源代码6 项目: rheem   文件: LogEvaluator.java
private void printPartialExecutions(String[] commandLine) {
    Stream<PartialExecution> stream = createPartialExecutionStream();
    if (commandLine.length >= 2) {
        stream = stream.limit(Long.parseLong(commandLine[1]));
    }
    stream.forEach(this::print);
}
 
源代码7 项目: dremio-oss   文件: MetadataProvider.java
@Override
public GetTablesResp execute() throws Exception {
  final Predicate<String> catalogNamePred = MetadataProviderConditions
    .getCatalogNamePredicate(req.hasCatalogNameFilter() ? req.getCatalogNameFilter() : null);
  final java.util.function.Predicate<String> tableTypePred = MetadataProviderConditions
    .getTableTypePredicate(req.getTableTypeFilterList());

  final Optional<SearchQuery> searchQuery = MetadataProviderConditions
    .createConjunctiveQuery(
      req.hasSchemaNameFilter() ? req.getSchemaNameFilter() : null,
      req.hasTableNameFilter() ? req.getTableNameFilter() : null);

  final ListTablesRequest.Builder requestBuilder = ListTablesRequest.newBuilder()
    .setUsername(parameters.getUsername());
  searchQuery.ifPresent(requestBuilder::setQuery);

  final Iterator<Table> tables = catalogStub.listTables(requestBuilder.build());

  Stream<TableMetadata> tableStream =
    StreamSupport.stream(Spliterators.spliteratorUnknownSize(tables, Spliterator.ORDERED), false)
      .map(table -> MetadataProviderUtils.toTableMetadata(table, parameters.getCatalogName()))
      .filter(table -> catalogNamePred.test(table.getCatalogName()) &&
        tableTypePred.test(table.getType()));

  if (parameters.getMaxMetadataCount() > 0) {
    tableStream = tableStream.limit(parameters.getMaxMetadataCount());
  }

  final List<TableMetadata> tableMetadata =
    tableStream.sorted(TABLES_ORDERING)  // reorder results according to JDBC/ODBC spec
      .collect(Collectors.toList());

  final GetTablesResp.Builder respBuilder = GetTablesResp.newBuilder();
  respBuilder.setQueryId(queryId);
  respBuilder.addAllTables(tableMetadata);
  respBuilder.setStatus(RequestStatus.OK);
  return respBuilder.build();
}
 
源代码8 项目: rdf4j   文件: OrderIterator.java
private Stream<BindingSet> sort(Collection<BindingSet> collection) {
	BindingSet[] array = collection.toArray(new BindingSet[collection.size()]);
	Arrays.parallelSort(array, comparator);
	Stream<BindingSet> stream = Stream.of(array);
	if (distinct) {
		stream = stream.distinct();
	}
	if (limit < Integer.MAX_VALUE) {
		stream = stream.limit(limit);
	}
	return stream;
}
 
源代码9 项目: robozonky   文件: PrimaryMarketplaceAccessor.java
@Override
public Collection<LoanDescriptor> getMarketplace() {
    Stream<Loan> loans = tenant.call(zonky -> zonky.getAvailableLoans(getIncrementalFilter()))
        .filter(l -> l.getMyInvestment()
            .isEmpty()); // re-investing would fail
    if (getMaximumItemsToRead().isPresent()) {
        int limit = getMaximumItemsToRead().orElseThrow();
        LOGGER.trace("Enforcing read limit of {} latest items.", limit);
        loans = loans.limit(limit);
    }
    return loans.map(LoanDescriptor::new)
        .collect(Collectors.toList());
}
 
源代码10 项目: mobi   文件: ExplorableDatasetRest.java
/**
 * Creates a Response which contains the proper paged details.
 *
 * @param uriInfo    The URI information of the request.
 * @param items      The total list of items that need to be sorted, limited, and offset.
 * @param comparator The Comparator which will be used to sort the items.
 * @param asc        Whether the sorting should be ascending or descending.
 * @param limit      The size of the page of items to return.
 * @param offset     The number of items to skip.
 * @param <T>        A class that extends Object.
 * @return A Response with a page of items that has been filtered, sorted, and limited and headers for the total
 *         size and links to the next and previous pages if present.
 */
private <T> Response createPagedResponse(UriInfo uriInfo, List<T> items, Comparator<T> comparator, boolean asc,
                                         int limit, int offset) {
    validatePaginationParams(limit, offset, items.size());
    Stream<T> stream = items.stream();
    if (!asc) {
        stream = stream.sorted(comparator.reversed());
    } else {
        stream = stream.sorted(comparator);
    }
    if (offset > 0) {
        stream = stream.skip(offset);
    }
    if (limit > 0) {
        stream = stream.limit(limit);
    }
    List<T> pagedItems = stream.collect(Collectors.toList());
    Response.ResponseBuilder builder = Response.ok(pagedItems).header("X-Total-Count", items.size());
    Links links = LinksUtils.buildLinks(uriInfo, pagedItems.size(), items.size(), limit, offset);
    if (links.getNext() != null) {
        builder = builder.link(links.getBase() + links.getNext(), "next");
    }
    if (links.getPrev() != null) {
        builder = builder.link(links.getBase() + links.getPrev(), "prev");
    }
    return builder.build();
}
 
源代码11 项目: sakai   文件: SampleUserDirectoryProvider.java
@Override
public List<UserEdit> searchExternalUsers(String criteria, int first, int last, UserFactory factory) {
	Stream<Info> stream = m_info.values().stream().filter(i -> i.contains(criteria));
	if (first != -1) {
		stream = stream.skip(first);
	}
	if (last != -1) {
		stream = stream.limit(last-first+1);
	}
	return stream.map(i -> {
		UserEdit edit = factory.newUser(i.id);
		return getUser(edit)?edit:null;
	}).filter(Objects::nonNull).collect(Collectors.toList());
}
 
源代码12 项目: molgenis   文件: PermissionCheckingDecorator.java
private Stream<E> skipAndLimitStream(Stream<E> entityStream, Query<E> q) {
  if (q.getOffset() > 0) {
    entityStream = entityStream.skip(q.getOffset());
  }
  if (q.getPageSize() > 0) {
    entityStream = entityStream.limit(q.getPageSize());
  }
  return entityStream;
}
 
源代码13 项目: packagedrone   文件: StreamArtifactLocator.java
private static <T extends ArtifactInformation> Stream<T> applyOptions ( Stream<T> stream, final SearchOptions options )
{
    if ( options.getSkip () > 0 )
    {
        stream = stream.skip ( options.getSkip () );
    }
    if ( options.getLimit () > 0 )
    {
        stream = stream.limit ( options.getLimit () );
    }
    return stream;
}
 
源代码14 项目: data-prep   文件: DataSetAPI.java
@RequestMapping(value = "/api/datasets", method = GET, produces = APPLICATION_JSON_VALUE)
@ApiOperation(value = "List data sets.", produces = APPLICATION_JSON_VALUE,
        notes = "Returns a list of data sets the user can use.")
@Timed
public Stream<DatasetDTO> list(
        @ApiParam(value = "Sort key (by name or date), defaults to 'date'.") @RequestParam(
                defaultValue = "creationDate") Sort sort,
        @ApiParam(value = "Order for sort key (desc or asc), defaults to 'desc'.") @RequestParam(
                defaultValue = "desc") Order order,
        @ApiParam(value = "Filter on name containing the specified name") @RequestParam(
                defaultValue = "") String name,
        @ApiParam(value = "Filter on certified data sets") @RequestParam(defaultValue = "false") boolean certified,
        @ApiParam(value = "Filter on favorite data sets") @RequestParam(defaultValue = "false") boolean favorite,
        @ApiParam(value = "Filter on recent data sets") @RequestParam(defaultValue = "false") boolean limit) {
    try {
        CertificationState certification = certified ? CERTIFIED : null;
        Boolean filterOnFavorite = favorite ? Boolean.TRUE : null;
        Stream<DatasetDTO> datasetStream = datasetClient.listDataSetMetadata(certification, filterOnFavorite);

        if (isNotBlank(name)) {
            datasetStream = datasetStream.filter(ds -> containsIgnoreCase(ds.getName(), name));
        }

        if (certified) {
            datasetStream = datasetStream.filter(dataset -> dataset.getCertification() == CERTIFIED);
        }

        if (limit) {
            datasetStream = datasetStream.limit(datasetListLimit);
        }

        return datasetStream //
                .sorted(SortAndOrderHelper.getDatasetDTOComparator(sort, order));
    } finally {
        LOG.info("listing datasets done [favorite: {}, certified: {}, name: {}, limit: {}]", favorite, certified,
                name, limit);
    }
}
 
源代码15 项目: heroic   文件: SearchTransformTest.java
public SearchTransformResult<SearchHit> createLimitSet(Integer limit, SearchHit[]... pages) {
    final Set<SearchHit> set = new HashSet<>();

    Stream<SearchHit> stream =
        Arrays.stream(pages).map(Arrays::stream).reduce(Stream.empty(), Stream::concat);

    if (limit != null) {
        stream = stream.limit(limit);
    }

    stream.forEach(set::add);

    return new SearchTransformResult<>(set, limit != null, scrollID);
}
 
源代码16 项目: data-prep   文件: LimitDataSetContent.java
@Override
public Stream<DataSetRow> stream(DataSetMetadata dataSetMetadata) {
    Stream<DataSetRow> dataSetRowStream = delegate.stream(dataSetMetadata, limit);
    // deal with dataset size limit (ignored if limit is <= 0)
    return dataSetRowStream.limit(limit);
}
 
源代码17 项目: onos   文件: EventsCommand.java
@Override
protected void doExecute() {
    EventHistoryService eventHistoryService = get(EventHistoryService.class);

    Stream<Event<?, ?>> events = eventHistoryService.history().stream();

    boolean dumpAll = all || !(mastership || device || link || topology || host || cluster || intent);

    if (!dumpAll) {
        Predicate<Event<?, ?>> filter = (defaultIs) -> false;

        if (mastership) {
            filter = filter.or(evt -> evt instanceof MastershipEvent);
        }
        if (device) {
            filter = filter.or(evt -> evt instanceof DeviceEvent);
        }
        if (link) {
            filter = filter.or(evt -> evt instanceof LinkEvent);
        }
        if (topology) {
            filter = filter.or(evt -> evt instanceof TopologyEvent);
        }
        if (host) {
            filter = filter.or(evt -> evt instanceof HostEvent);
        }
        if (cluster) {
            filter = filter.or(evt -> evt instanceof ClusterEvent);
        }
        if (intent) {
            filter = filter.or(evt -> evt instanceof IntentEvent);
        }

        events = events.filter(filter);
    }

    if (maxSize > 0) {
        events = events.limit(maxSize);
    }

    if (outputJson()) {
        ArrayNode jsonEvents = events.map(this::json).collect(toArrayNode());
        printJson(jsonEvents);
    } else {
        events.forEach(this::printEvent);
    }

}
 
源代码18 项目: unix-stream   文件: Head.java
@Override
public Stream<T> apply(Stream<T> input) {
    return input.limit(size);
}
 
源代码19 项目: vertexium   文件: HistoricalEventsFetchHints.java
public Stream<HistoricalEvent> applyToResults(Stream<HistoricalEvent> events, HistoricalEventId after) {
    switch (getSortDirection()) {
        case ASCENDING:
            events = events.sorted();
            break;
        case DESCENDING:
            events = events.sorted((o1, o2) -> -o1.compareTo(o2));
            break;
        default:
            throw new VertexiumException("Unhandled sort direction: " + getSortDirection());
    }

    if (startTime != null || endTime != null) {
        long startTimeMillis = startTime == null ? 0 : startTime.toInstant().toEpochMilli();
        long endTimeMillis = endTime == null ? Long.MAX_VALUE : endTime.toInstant().toEpochMilli();
        events = events.filter(event -> {
            long ts = event.getTimestamp().toInstant().toEpochMilli();
            if (ts < startTimeMillis) {
                return false;
            }
            if (ts > endTimeMillis) {
                return false;
            }
            return true;
        });
    }

    if (after != null) {
        events = events.filter(event -> {
            int i = event.getHistoricalEventId().compareTo(after);
            switch (getSortDirection()) {
                case ASCENDING:
                    return i > 0;
                case DESCENDING:
                    return i < 0;
                default:
                    throw new VertexiumException("Unhandled sort direction: " + getSortDirection());
            }
        });
    }

    if (limit != null) {
        events = events.limit(limit);
    }

    return events;
}
 
源代码20 项目: heroic   文件: ValueOptionalLimit.java
@Override
public <T> Stream<T> limitStream(final Stream<T> stream) {
    return stream.limit(limit);
}