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

The following examples show how to use java.util.stream.Stream#sorted() . 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
@Override
public Stream<HUEditorRow> streamPage(
		final int firstRow,
		final int pageLength,
		@NonNull final HUEditorRowFilter filter,
		@NonNull final ViewRowsOrderBy orderBys)
{
	final ViewRowsOrderBy orderBysEffective = !orderBys.isEmpty()
			? orderBys
			: orderBys.withOrderBys(defaultOrderBys);

	Stream<HUEditorRow> stream = getRows().stream()
			.skip(firstRow)
			.limit(pageLength)
			.filter(HUEditorRowFilters.toPredicate(filter));

	final Comparator<HUEditorRow> comparator = orderBysEffective.toComparatorOrNull();
	if (comparator != null)
	{
		stream = stream.sorted(comparator);
	}

	return stream;
}
 
Example 2
public static final JSONLookupValuesList ofLookupValuesList(
		@Nullable final LookupValuesList lookupValues,
		@NonNull final String adLanguage)
{
	if (lookupValues == null || lookupValues.isEmpty())
	{
		return EMPTY;
	}

	Stream<JSONLookupValue> jsonValues = lookupValues.getValues()
			.stream()
			.map(lookupValue -> JSONLookupValue.ofLookupValue(lookupValue, adLanguage));

	if (!lookupValues.isOrdered())
	{
		jsonValues = jsonValues.sorted(Comparator.comparing(JSONLookupValue::getCaption));
	}

	final ImmutableList<JSONLookupValue> jsonValuesList = jsonValues.collect(ImmutableList.toImmutableList());
	final DebugProperties otherProperties = lookupValues.getDebugProperties();
	return new JSONLookupValuesList(jsonValuesList, otherProperties);
}
 
Example 3
Source Project: flow   File: TreeDataProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Stream<T> fetchChildren(
        HierarchicalQuery<T, SerializablePredicate<T>> query) {
    if (!treeData.contains(query.getParent())) {
        throw new IllegalArgumentException("The queried item "
                + query.getParent()
                + " could not be found in the backing TreeData. "
                + "Did you forget to refresh this data provider after item removal?");
    }

    Stream<T> childStream = getFilteredStream(
            treeData.getChildren(query.getParent()).stream(),
            query.getFilter());

    Optional<Comparator<T>> comparing = Stream
            .of(query.getInMemorySorting(), sortOrder)
            .filter(Objects::nonNull)
            .reduce((c1, c2) -> c1.thenComparing(c2));

    if (comparing.isPresent()) {
        childStream = childStream.sorted(comparing.get());
    }

    return childStream.skip(query.getOffset()).limit(query.getLimit());
}
 
Example 4
Source Project: lucene-solr   File: SimpleFacets.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Computes the term-&gt;count counts for the specified term values relative to the
 *
 * @param field the name of the field to compute term counts against
 * @param parsed contains the docset to compute term counts relative to
 * @param terms a list of term values (in the specified field) to compute the counts for
 */
protected NamedList<Integer> getListedTermCounts(String field, final ParsedParams parsed, List<String> terms)
    throws IOException {
  final String sort = parsed.params.getFieldParam(field, FacetParams.FACET_SORT, "empty");
  final SchemaField sf = searcher.getSchema().getField(field);
  final FieldType ft = sf.getType();
  final DocSet baseDocset = parsed.docs;
  final NamedList<Integer> res = new NamedList<>();
  Stream<String> inputStream = terms.stream();
  if (sort.equals(FacetParams.FACET_SORT_INDEX)) { // it might always make sense
    inputStream = inputStream.sorted();
  }
  Stream<SimpleImmutableEntry<String,Integer>> termCountEntries = inputStream
      .map((term) -> new SimpleImmutableEntry<>(term, numDocs(term, sf, ft, baseDocset)));
  if (sort.equals(FacetParams.FACET_SORT_COUNT)) {
    termCountEntries = termCountEntries.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()));
  }
  termCountEntries.forEach(e -> res.add(e.getKey(), e.getValue()));
  return res;
}
 
Example 5
/**
 * {@inheritDoc}
 */
@Override public BinaryClassificationEvaluationContext<L> mergeWith(
    BinaryClassificationEvaluationContext<L> other) {
    checkNewLabel(other.firstClsLbl);
    checkNewLabel(other.secondClsLbl);

    List<L> uniqLabels = new ArrayList<>(4);
    uniqLabels.add(this.firstClsLbl);
    uniqLabels.add(this.secondClsLbl);
    uniqLabels.add(other.firstClsLbl);
    uniqLabels.add(other.secondClsLbl);
    Stream<L> s = uniqLabels.stream().filter(Objects::nonNull).distinct();
    if (firstClsLbl instanceof Comparable || secondClsLbl instanceof Comparable ||
        other.firstClsLbl instanceof Comparable || other.secondClsLbl instanceof Comparable)
        s = s.sorted();
    uniqLabels = s.collect(Collectors.toList());

    A.ensure(uniqLabels.size() < 3, "labels.length < 3");
    return new BinaryClassificationEvaluationContext<>(
        uniqLabels.isEmpty() ? null : uniqLabels.get(0),
        uniqLabels.size() < 2 ? null : uniqLabels.get(1)
    );
}
 
Example 6
Source Project: camelinaction2   File: GoalEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Consumer createConsumer(Processor processor) throws Exception {
    // load goals from resource
    InputStream is = getResourceAsInputStream();
    String text = IOHelper.loadText(is);

    // split each line
    Stream<String> stream = Arrays.stream(text.split("\n"));

    // sort goals scored on minutes
    stream = stream.sorted((a, b) -> goalTime(a).compareTo(goalTime(b)));

    // store goals in a list
    List<String> goals = stream.collect(Collectors.toList());

    // create consumer with the goals
    return new GoalConsumer(this, processor, goals);
}
 
Example 7
Source Project: FunnyGuilds   File: MapUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean descending) {
    Stream<Entry<K, V>> stream = map.entrySet().stream();

    if (descending) {
        stream = stream.sorted(Entry.comparingByValue(Collections.reverseOrder()));
    } else {
        stream = stream.sorted(Entry.comparingByValue());
    }

    return stream.collect(Collectors.toMap(Entry::getKey, Entry::getValue, (firstEntry, secondEntry) -> firstEntry, LinkedHashMap::new));
}
 
Example 8
Source Project: arcusplatform   File: FilteredViewModel.java    License: Apache License 2.0 5 votes vote down vote up
protected void rebuildView() {
   Stream<M> stream = StreamSupport.stream(delegate.spliterator(), false);
   if(filter != null) {
      stream = stream.filter(filter);
   }
   if(comparator != null) {
      stream = stream.sorted(comparator);
   }
   this.view = stream.collect(Collectors.toList());
   this.listeners.fireEvent(ViewModelEvent.changed());
}
 
Example 9
Source Project: batfish   File: WorkMgr.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
@Nonnull
TableAnswerElement processAnswerTable(TableAnswerElement rawTable, AnswerRowsOptions options) {
  Map<String, ColumnMetadata> rawColumnMap = rawTable.getMetadata().toColumnMap();
  List<Row> filteredRows =
      rawTable.getRowsList().stream()
          .filter(row -> options.getFilters().stream().allMatch(filter -> filter.matches(row)))
          .collect(ImmutableList.toImmutableList());

  Stream<Row> rowStream = filteredRows.stream();
  if (!options.getSortOrder().isEmpty()) {
    // sort using specified sort order
    rowStream = rowStream.sorted(buildComparator(rawColumnMap, options.getSortOrder()));
  }
  TableAnswerElement table;
  if (options.getColumns().isEmpty()) {
    table = new TableAnswerElement(rawTable.getMetadata());
  } else {
    // project to desired columns
    rowStream =
        rowStream.map(rawRow -> Row.builder().putAll(rawRow, options.getColumns()).build());
    Map<String, ColumnMetadata> columnMap = new LinkedHashMap<>(rawColumnMap);
    columnMap.keySet().retainAll(options.getColumns());
    List<ColumnMetadata> columnMetadata =
        columnMap.values().stream().collect(ImmutableList.toImmutableList());
    table =
        new TableAnswerElement(
            new TableMetadata(columnMetadata, rawTable.getMetadata().getTextDesc()));
  }
  if (options.getUniqueRows()) {
    // uniquify if desired
    rowStream = rowStream.distinct();
  }
  // offset, truncate, and add to table
  rowStream.skip(options.getRowOffset()).limit(options.getMaxRows()).forEach(table::addRow);
  table.setSummary(rawTable.getSummary() != null ? rawTable.getSummary() : new AnswerSummary());
  table.getSummary().setNumResults(filteredRows.size());
  return table;
}
 
Example 10
Source Project: spring-vault   File: VaultQueryEngine.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> Collection<T> execute(@Nullable VaultQuery vaultQuery, @Nullable Comparator<?> comparator, long offset,
		int rows, String keyspace, Class<T> type) {

	Stream<String> stream = getRequiredAdapter().doList(keyspace).stream();

	if (vaultQuery != null) {
		stream = stream.filter(vaultQuery::test);
	}

	if (comparator == null) {

		if (offset > 0) {
			stream = stream.skip(offset);
		}

		if (rows > 0) {
			stream = stream.limit(rows);
		}
	}

	Stream<T> typed = stream.map(it -> getRequiredAdapter().get(it, keyspace, type));

	if (comparator != null) {

		typed = typed.sorted((Comparator) comparator);

		if (offset > 0) {
			typed = typed.skip(offset);
		}

		if (rows > 0) {
			typed = typed.limit(rows);
		}
	}

	return typed.collect(Collectors.toCollection(ArrayList::new));
}
 
Example 11
void filter()
{
	if (refreshing.isVisible())
	{
		return;
	}

	mainPanel.removeAll();

	Stream<PluginItem> stream = plugins.stream();

	String search = searchBar.getText();
	boolean isSearching = search != null && !search.trim().isEmpty();
	if (isSearching)
	{
		String[] searchArray = SPACES.split(search.toLowerCase());
		stream = stream
			.filter(p -> Text.matchesSearchTerms(searchArray, p.keywords))
			.sorted(Comparator.comparing(p -> p.manifest.getDisplayName()));
	}
	else
	{
		stream = stream
			.sorted(Comparator.comparing(PluginItem::isInstalled).thenComparing(p -> p.manifest.getDisplayName()));
	}

	stream.forEach(mainPanel::add);
	mainPanel.revalidate();
}
 
Example 12
Source Project: FunnyGuilds   File: MapUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static <K extends Comparable<? super K>, V> Map<K, V> sortByKey(Map<K, V> map, boolean descending) {
    Stream<Entry<K, V>> stream = map.entrySet().stream();

    if (descending) {
        stream = stream.sorted(Entry.comparingByKey(Collections.reverseOrder()));
    } else {
        stream = stream.sorted(Entry.comparingByKey());
    }

    return stream.collect(Collectors.toMap(Entry::getKey, Entry::getValue, (firstEntry, secondEntry) -> secondEntry, LinkedHashMap::new));
}
 
Example 13
/**
 * 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 14
Source Project: flow   File: ListDataProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Stream<T> fetch(Query<T, SerializablePredicate<T>> query) {
    Stream<T> stream = getFilteredStream(query);

    Optional<Comparator<T>> comparing = Stream
            .of(query.getInMemorySorting(), sortOrder)
            .filter(Objects::nonNull)
            .reduce((c1, c2) -> c1.thenComparing(c2));

    if (comparing.isPresent()) {
        stream = stream.sorted(comparing.get());
    }

    return stream.skip(query.getOffset()).limit(query.getLimit());
}
 
Example 15
Source Project: Flink-CEPplus   File: CepOperator.java    License: Apache License 2.0 4 votes vote down vote up
private Stream<IN> sort(Collection<IN> elements) {
	Stream<IN> stream = elements.stream();
	return (comparator == null) ? stream : stream.sorted(comparator);
}
 
Example 16
Source Project: unix-stream   File: Sort.java    License: MIT License 4 votes vote down vote up
@Override
public Stream<T> apply(Stream<T> input) {
    return comparator != null ? input.sorted(comparator) : input.sorted();
}
 
Example 17
private Stream<IteratorHistoricalEvent> applyToResults(
    Stream<IteratorHistoricalEvent> events,
    IteratorHistoricalEventsFetchHints fetchHints,
    HistoricalEventId after
) {
    switch (fetchHints.getSortDirection()) {
        case ASCENDING:
            events = events.sorted();
            break;
        case DESCENDING:
            events = events.sorted((o1, o2) -> -o1.compareTo(o2));
            break;
        default:
            throw new VertexiumAccumuloIteratorException("Unhandled sort direction: " + fetchHints.getSortDirection());
    }

    if (fetchHints.getStartTime() != null || fetchHints.getEndTime() != null) {
        long startTimeMillis = fetchHints.getStartTime() == null ? 0 : fetchHints.getStartTime();
        long endTimeMillis = fetchHints.getEndTime() == null ? Long.MAX_VALUE : fetchHints.getEndTime();
        events = events.filter(event -> {
            long ts = event.getTimestamp();
            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 (fetchHints.getSortDirection()) {
                case ASCENDING:
                    return i > 0;
                case DESCENDING:
                    return i < 0;
                default:
                    throw new VertexiumAccumuloIteratorException("Unhandled sort direction: " + fetchHints.getSortDirection());
            }
        });
    }

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

    return events;
}
 
Example 18
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 19
Source Project: data-prep   File: DataSetService.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Return the list of DataSetMetadata corresponding to the search
 *
 * @param sort sort filter
 * @param order order filter
 * @param name name filter
 * @param nameStrict is it a strict search
 * @param certified certified filter
 * @param favorite favorite filter
 * @param limit limit number of result
 * @param favoritesIds list of favorties ids of the user
 * @return the list of DataSetMetadata corresponding to the search
 */
private Stream<DataSetMetadata> findDataset(Sort sort, Order order, String name, boolean nameStrict,
        boolean certified, boolean favorite, boolean limit, Set<String> favoritesIds) {
    // Build filter for data sets
    final List<String> predicates = new ArrayList<>();
    predicates.add("lifecycle.importing = false");
    if (favorite) {
        if (favoritesIds != null && !favoritesIds.isEmpty()) {
            predicates.add("id in ["
                    + favoritesIds.stream().map(ds -> '\'' + ds + '\'').collect(Collectors.joining(",")) + "]");
        } else {
            // Wants favorites but user has no favorite
            return Stream.empty();
        }
    }
    if (certified) {
        predicates.add("governance.certificationStep = '" + Certification.CERTIFIED + "'");
    }

    if (StringUtils.isNotEmpty(name)) {
        final String regex = "(?i)" + Pattern.quote(name);
        final String filter;
        if (nameStrict) {
            filter = "name ~ '^" + regex + "$'";
        } else {
            filter = "name ~ '.*" + regex + ".*'";
        }
        predicates.add(filter);
    }

    final String tqlFilter = String.join(" and ", predicates);
    LOG.debug("TQL Filter in use: {}", tqlFilter);

    // Get all data sets according to filter
    Stream<DataSetMetadata> datasetList = dataSetMetadataRepository.list(tqlFilter, sort, order);

    if (sort == Sort.AUTHOR || sort == Sort.NAME) { // As theses are not well handled by mongo repository
        datasetList = datasetList.sorted(getDataSetMetadataComparator(sort, order));
    }

    return datasetList.limit(limit ? datasetListLimit : Long.MAX_VALUE);
}
 
Example 20
/**
 * Performs pagination on the {@code list}, returning from the specified {@code offset} to the specified
 * {@code limit}. The list can also be sorted by the {@code sortBy} (optional).
 *
 * @param list      the list to paginate
 * @param offset    the offset from where to start
 * @param limit     the max number of elements that the paginated list should include
 * @param sortBy    the property used for sorting
 *
 * @return the paginated list
 */
public static <T> List<T> paginate(List<T> list, int offset, int limit, String sortBy) {
    Stream<T> stream = list.stream();

    if (StringUtils.isNotEmpty(sortBy)) {
        stream = stream.sorted(new BeanComparator<>(sortBy));
    }

    return stream.skip(offset).limit(limit).collect(Collectors.toList());
}