List of usage examples for java.util.stream Stream sorted
Stream<T> sorted(Comparator<? super T> comparator);
From source file:Main.java
/** * Sorts a Map by it's value// w w w . ja v a 2 s . co m * * @param map Map * @param <K> Key * @param <V> Value * @return The sorted map */ public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { Map<K, V> result = new LinkedHashMap<>(); Stream<Map.Entry<K, V>> st = map.entrySet().stream(); st.sorted(Comparator.comparing(Map.Entry::getValue)) .forEachOrdered(e -> result.put(e.getKey(), e.getValue())); return result; }
From source file:TwitterClustering.java
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { Map<K, V> result = new LinkedHashMap<>(); Stream<Map.Entry<K, V>> st = map.entrySet().stream(); st.sorted(Comparator.comparing(e -> e.getValue())).forEach(e -> result.put(e.getKey(), e.getValue())); return result; }
From source file:com.yahoo.bard.webservice.util.SimplifiedIntervalList.java
/** * Takes one or more lists of intervals, and combines them into a single, sorted list with the minimum number of * intervals needed to capture exactly the same instants as the original intervals. * <p>/* ww w . ja v a 2 s . c o m*/ * If any subintervals of the input collection abut or overlap they will be replaced with a single, combined * interval. * <p> * Examples: * <ul> * <li>['2014/2017', '2015/2020'] will combine into ['2014/2020'] * <li>['2015/2016', '2016/2017'] will combine into ['2015/2017] * <li>['2015/2016', '2013/2014'] will sort into ['2013/2014', '2015/2016'] * <li>['2015/2015', '2015/2016', '2012/2013'] will sort and combine to ['2012/2013', '2015/2016'] * </ul> * @param intervals The collection(s) of intervals being collated * * @return A single list of sorted intervals simplified to the smallest number of intervals able to describe the * duration */ @SafeVarargs public static SimplifiedIntervalList simplifyIntervals(Collection<Interval>... intervals) { Stream<Interval> allIntervals = Stream.empty(); for (Collection<Interval> intervalCollection : intervals) { allIntervals = Stream.concat(allIntervals, intervalCollection.stream()); } return allIntervals.sorted(IntervalStartComparator.INSTANCE::compare).collect(getCollector()); }
From source file:com.liferay.apio.architect.impl.jaxrs.json.reader.MultipartBodyMessageBodyReader.java
private <T> Map<String, List<T>> _flattenMap(Map<String, Map<Integer, T>> indexedValueLists) { Set<Entry<String, Map<Integer, T>>> entries = indexedValueLists.entrySet(); Stream<Entry<String, Map<Integer, T>>> stream = entries.stream(); return stream.sorted(comparingByKey()).collect(Collectors.toMap(Entry::getKey, v -> { Map<Integer, T> map = v.getValue(); return new ArrayList<>(map.values()); }));/*from w w w. j a va 2 s .com*/ }
From source file:onl.area51.gfs.grib2.job.GribRetriever.java
/** * Select the specified run./*from www . j a v a 2 s .c om*/ * <p> * @param date The date and hour of the required run * <p> * @throws java.io.IOException */ public void selectRun(LocalDateTime date) throws IOException { LOG.log(Level.INFO, "Retrieving directory listing"); client.changeWorkingDirectory(DIR); Stream<FTPFile> dirs = client.directories().filter(f -> f.getName().startsWith("gfs.")); if (date == null) { // Look for the most recent date dirs = dirs.sorted((a, b) -> b.getName().compareToIgnoreCase(a.getName())); } else { // Look for a specific date String filter = "gfs." + toGFSRunTime(date).format(DateTimeFormatter.BASIC_ISO_DATE); dirs = dirs.filter(f -> filter.equals(f.getName())); } @SuppressWarnings("ThrowableInstanceNotThrown") FTPFile dir = dirs.findFirst() .orElseThrow(() -> new FileNotFoundException("Failed to find remote gfs directory ")); client.changeWorkingDirectory(dir.getName()); String pwd = client.printWorkingDirectory(); LOG.log(Level.INFO, () -> "Now in directory " + pwd); }
From source file:com.searchcode.app.util.Helpers.java
/** * Sorts a map by value taken from/*from www . j a v a 2 s . c o m*/ * http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java */ public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { Map<K, V> result = new LinkedHashMap<>(); Stream<Map.Entry<K, V>> st = map.entrySet().stream(); st.sorted(Map.Entry.comparingByValue()).forEachOrdered(e -> result.put(e.getKey(), e.getValue())); return result; }
From source file:de.tudarmstadt.ukp.dkpro.core.frequency.phrasedetection.FrequencyCounter.java
/** * Write counter with counts from a bag to an output stream. * * @param os an {@link OutputStream} * @param counter a {@link Bag} of string counter *//*from w w w . ja v a 2 s .c om*/ private void writeNgrams(OutputStream os, Bag<String> counter) { /* create token stream */ Stream<String> stream = counter.uniqueSet().stream().filter(token -> counter.getCount(token) >= minCount); /* sort output */ if (sortByAlphabet) { stream = stream.sorted(String::compareTo); } else if (sortByCount) { stream = stream.sorted((o1, o2) -> -Integer.compare(counter.getCount(o1), counter.getCount(o2))); } /* write tokens with counts */ stream.forEach(token -> { try { os.write((token + COLUMN_SEPARATOR + counter.getCount(token) + "\n").getBytes()); } catch (IOException e) { throw new RuntimeException(e); } }); }
From source file:org.ow2.proactive.scheduling.api.graphql.fetchers.DatabaseConnectionFetcher.java
/** * Adaptation of the algorithm defined in the GraphQL specification. * <p>/*from w ww . j a v a 2 s .co m*/ * Please look at the following link for more details: * https://facebook.github.io/relay/graphql/connections.htm#sec-Pagination-algorithm * <p> * The opaque cursor that is returned to the client makes use of the entity ID internally. */ protected ExtendedConnection createPaginatedConnection(DataFetchingEnvironment environment, Class<E> entityClass, Function<Root<E>, Path<? extends Number>> entityId, Comparator<E> entityComparator, BiFunction<CriteriaBuilder, Root<E>, List<Predicate[]>> criteria, CursorMapper<T, Integer> cursorMapper) { Integer first = environment.getArgument(FIRST.getName()); Integer last = environment.getArgument(LAST.getName()); Integer after = cursorMapper.getOffsetFromCursor(environment.getArgument(AFTER.getName())); Integer before = cursorMapper.getOffsetFromCursor(environment.getArgument(BEFORE.getName())); CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<E> criteriaQuery = criteriaBuilder.createQuery(entityClass); Root<E> entityRoot = criteriaQuery.from(entityClass); Path<? extends Number> entityIdPath = entityId.apply(entityRoot); Predicate cursorPredicate = createCursorPredicate(criteriaBuilder, entityIdPath, after, before); int maxResults = applySlicing(criteriaQuery, criteriaBuilder, entityIdPath, first, last); CriteriaQuery<E> select = criteriaQuery.select(entityRoot); List<Predicate[]> predicates = criteria.apply(criteriaBuilder, entityRoot); Predicate[] wherePredicate = buildWherePredicate(predicates, cursorPredicate, criteriaBuilder); if (wherePredicate.length > 0) { select.where(wherePredicate); } TypedQuery<E> query = entityManager.createQuery(select); if (maxResults > -1) { query.setMaxResults(maxResults); } Stream<E> dataStream = query.getResultList().stream(); // if last is provided, reverse the stream // in order to get results sorted in ascending order based on entities ID if (last != null) { dataStream = dataStream.sorted(entityComparator); } Stream<T> data = dataMapping(dataStream); ExtendedConnection connection = createRelayConnection(entityManager, entityClass, criteriaBuilder, wherePredicate, cursorMapper, data, first, last); return connection; }
From source file:de.unihannover.l3s.mws.bean.Hackathon.java
public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { Map<K, V> result = new LinkedHashMap<>(); Stream<Entry<K, V>> st = map.entrySet().stream(); st.sorted(Comparator.comparing(e -> e.getValue())) .forEachOrdered(e -> result.put(e.getKey(), e.getValue())); return result; }
From source file:com.streamsets.datacollector.bundles.SupportBundleManager.java
/** * Orchestrate what definitions should be used for this bundle. * * Either get all definitions that should be used by default or only those specified in the generators argument. *//*from w w w .j ava2 s . c om*/ private List<BundleContentGeneratorDefinition> getRequestedDefinitions(List<String> generators) { Stream<BundleContentGeneratorDefinition> stream = definitions.stream(); if (generators == null || generators.isEmpty()) { // Filter out default generators stream = stream.filter(BundleContentGeneratorDefinition::isEnabledByDefault); } else { stream = stream.filter(def -> generators.contains(def.getId())); } return stream.sorted(Comparator.comparingInt(BundleContentGeneratorDefinition::getOrder)) .collect(Collectors.toList()); }