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

The following examples show how to use java.util.stream.Stream#limit() . 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: AttributeRepositorySecurityDecorator.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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;
  }
}
 
Example 2
Source File: SpelQueryEngine.java    From spring-data-keyvalue with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example 3
Source File: RelationExtractor.java    From rdf2x with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 4
Source File: BaseInMemoryRepository.java    From business with Mozilla Public License 2.0 6 votes vote down vote up
@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;
}
 
Example 5
Source File: SearchTransformTest.java    From heroic with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 6
Source File: PrestoResultSet.java    From presto with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 7
Source File: DataSetAPI.java    From data-prep with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 8
Source File: StreamArtifactLocator.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example 9
Source File: PermissionCheckingDecorator.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 10
Source File: SampleUserDirectoryProvider.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@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());
}
 
Example 11
Source File: ExplorableDatasetRest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 12
Source File: PrimaryMarketplaceAccessor.java    From robozonky with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 13
Source File: OrderIterator.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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;
}
 
Example 14
Source File: MetadataProvider.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 15
Source File: LogEvaluator.java    From rheem with Apache License 2.0 5 votes vote down vote up
private void printPartialExecutions(String[] commandLine) {
    Stream<PartialExecution> stream = createPartialExecutionStream();
    if (commandLine.length >= 2) {
        stream = stream.limit(Long.parseLong(commandLine[1]));
    }
    stream.forEach(this::print);
}
 
Example 16
Source File: Head.java    From unix-stream with MIT License 4 votes vote down vote up
@Override
public Stream<T> apply(Stream<T> input) {
    return input.limit(size);
}
 
Example 17
Source File: HistoricalEventsFetchHints.java    From vertexium with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example 18
Source File: EventsCommand.java    From onos with Apache License 2.0 4 votes vote down vote up
@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);
    }

}
 
Example 19
Source File: ValueOptionalLimit.java    From heroic with Apache License 2.0 4 votes vote down vote up
@Override
public <T> Stream<T> limitStream(final Stream<T> stream) {
    return stream.limit(limit);
}
 
Example 20
Source File: LimitDataSetContent.java    From data-prep with Apache License 2.0 4 votes vote down vote up
@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);
}