List of usage examples for java.util Comparator comparing
public static <T, U extends Comparable<? super U>> Comparator<T> comparing( Function<? super T, ? extends U> keyExtractor)
From source file:org.silverpeas.core.admin.domain.driver.googledriver.GoogleDirectoryRequester.java
public List<User> users() throws AdminException { try {// w ww. j ava 2 s . c o m List<User> result = new LinkedList<>(); final long start = System.currentTimeMillis(); final Directory.Users.List users = getDirectoryService().users().list().setMaxResults(QUERY_MAX_RESULTS) .setCustomer(MY_CUSTOMER).setProjection("full"); String pageToken = null; while (true) { final Users currentUsers = users.setPageToken(pageToken).execute(); pageToken = currentUsers.getNextPageToken(); final List<User> currentResult = currentUsers.getUsers(); result.addAll(currentResult); if (currentResult.size() < QUERY_MAX_RESULTS || pageToken == null) { break; } } result = applyFilter(result); result.sort(Comparator.comparing((User g) -> g.getName().getFamilyName().toLowerCase()) .thenComparing(g -> g.getName().getGivenName().toLowerCase())); final long end = System.currentTimeMillis(); SilverLogger.getLogger(this).debug(() -> MessageFormat.format("Getting accounts in {0}", DurationFormatUtils.formatDurationHMS(end - start))); return result; } catch (IOException e) { throw new AdminException(e); } }
From source file:com.epam.dlab.module.aws.S3FileList.java
private Stream<? extends String> lastFileForBillingPeriod(Map.Entry<String, List<S3ObjectSummary>> entry) { final List<S3ObjectSummary> assemblyIds = entry.getValue(); final S3ObjectSummary lastBillingFile = assemblyIds.stream() .max(Comparator.comparing(S3ObjectSummary::getLastModified)) .orElseThrow(() -> new IllegalStateException("AssemblyId does not contains any file")); return assemblyIds.stream() .filter(s -> s.getKey().startsWith(StringUtils.substringBeforeLast(lastBillingFile.getKey(), "/"))) .map(S3ObjectSummary::getKey); }
From source file:org.ajoberstar.reckon.core.git.GitInventorySupplier.java
private Optional<TaggedVersion> findCurrent(RevCommit head, Stream<TaggedVersion> versions) { return versions.filter(version -> version.getCommit().equals(head)) .max(Comparator.comparing(TaggedVersion::getVersion)); }
From source file:org.egov.pgr.dashboard.service.DashboardService.java
private static void sortData(List<Map<String, Object>> dataList, String key) { Collections.sort(dataList, Comparator.comparing(map -> Double.valueOf(map.get(key).toString()))); }
From source file:org.apache.nifi.minifi.c2.provider.delegating.DelegatingConfigurationProvider.java
protected HttpURLConnection getDelegateConnection(String contentType, Map<String, List<String>> parameters) throws ConfigurationProviderException { StringBuilder queryStringBuilder = new StringBuilder(); try {/* www . j a v a 2 s . c o m*/ parameters.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey)) .forEachOrdered(e -> e.getValue().stream().sorted().forEachOrdered(v -> { try { queryStringBuilder.append(URLEncoder.encode(e.getKey(), "UTF-8")).append("=") .append(URLEncoder.encode(v, "UTF-8")); } catch (UnsupportedEncodingException ex) { throw new ConfigurationProviderException("Unsupported encoding.", ex).wrap(); } queryStringBuilder.append("&"); })); } catch (ConfigurationProviderException.Wrapper e) { throw e.unwrap(); } String url = "/c2/config"; if (queryStringBuilder.length() > 0) { queryStringBuilder.setLength(queryStringBuilder.length() - 1); url = url + "?" + queryStringBuilder.toString(); } HttpURLConnection httpURLConnection = httpConnector.get(url); httpURLConnection.setRequestProperty("Accepts", contentType); try { int responseCode; try { responseCode = httpURLConnection.getResponseCode(); } catch (IOException e) { Matcher matcher = errorPattern.matcher(e.getMessage()); if (matcher.matches()) { responseCode = Integer.parseInt(matcher.group(1)); } else { throw e; } } if (responseCode >= 400) { String message = ""; InputStream inputStream = httpURLConnection.getErrorStream(); if (inputStream != null) { try { message = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } finally { inputStream.close(); } } if (responseCode == 400) { throw new InvalidParameterException(message); } else if (responseCode == 403) { throw new AuthorizationException("Got authorization exception from upstream server " + message); } else { throw new ConfigurationProviderException(message); } } } catch (IOException e) { throw new ConfigurationProviderException("Unable to get response code from upstream server.", e); } return httpURLConnection; }
From source file:no.imr.stox.functions.acoustic.PgNapesIO.java
public static void export2(String cruise, String country, String callSignal, String path, String fileName, List<DistanceBO> distances, Double groupThickness, Integer freqFilter, String specFilter, boolean withZeros) { Set<Integer> freqs = distances.stream().flatMap(dist -> dist.getFrequencies().stream()) .map(FrequencyBO::getFreq).collect(Collectors.toSet()); if (freqFilter == null && freqs.size() == 1) { freqFilter = freqs.iterator().next(); }//from w w w . ja v a 2 s. com if (freqFilter == null) { System.out.println("Multiple frequencies, specify frequency filter as parameter"); return; } Integer freqFilterF = freqFilter; // ef.final List<String> acList = distances.parallelStream().flatMap(dist -> dist.getFrequencies().stream()) .filter(fr -> freqFilterF.equals(fr.getFreq())).map(f -> { DistanceBO d = f.getDistanceBO(); LocalDateTime sdt = LocalDateTime.ofInstant(d.getStart_time().toInstant(), ZoneOffset.UTC); Double intDist = d.getIntegrator_dist(); String month = StringUtils.leftPad(sdt.getMonthValue() + "", 2, "0"); String day = StringUtils.leftPad(sdt.getDayOfMonth() + "", 2, "0"); String hour = StringUtils.leftPad(sdt.getHour() + "", 2, "0"); String minute = StringUtils.leftPad(sdt.getMinute() + "", 2, "0"); String log = Conversion.formatDoubletoDecimalString(d.getLog_start(), "0.0"); String acLat = Conversion.formatDoubletoDecimalString(d.getLat_start(), "0.000"); String acLon = Conversion.formatDoubletoDecimalString(d.getLon_start(), "0.000"); return Stream .of(d.getNation(), d.getPlatform(), d.getCruise(), log, sdt.getYear(), month, day, hour, minute, acLat, acLon, intDist, f.getFreq(), f.getThreshold()) .map(o -> o == null ? "" : o.toString()).collect(Collectors.joining("\t")) + "\t"; }).collect(Collectors.toList()); String fil1 = path + "/" + fileName + ".txt"; acList.add(0, Stream.of("Country", "Vessel", "Cruise", "Log", "Year", "Month", "Day", "Hour", "Min", "AcLat", "AcLon", "Logint", "Frequency", "Sv_threshold").collect(Collectors.joining("\t"))); try { Files.write(Paths.get(fil1), acList, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException ex) { Logger.getLogger(PgNapesIO.class.getName()).log(Level.SEVERE, null, ex); } acList.clear(); // Acoustic values distances.stream().filter(d -> d.getPel_ch_thickness() != null) .flatMap(dist -> dist.getFrequencies().stream()).filter(fr -> freqFilterF.equals(fr.getFreq())) .forEachOrdered(f -> { try { Double groupThicknessF = Math.max(f.getDistanceBO().getPel_ch_thickness(), groupThickness); Map<String, Map<Integer, Double>> pivot = f.getSa().stream() .filter(s -> s.getCh_type().equals("P")).map(s -> new SAGroup(s, groupThicknessF)) .filter(s -> s.getSpecies() != null && (specFilter == null || specFilter.equals(s.getSpecies()))) // create pivot table: species (dim1) -> depth interval index (dim2) -> sum sa (group aggregator) .collect(Collectors.groupingBy(SAGroup::getSpecies, Collectors.groupingBy( SAGroup::getDepthGroupIdx, Collectors.summingDouble(SAGroup::sa)))); if (pivot.isEmpty() && specFilter != null && withZeros) { pivot.put(specFilter, new HashMap<>()); } Integer maxGroupIdx = pivot.entrySet().stream().flatMap(e -> e.getValue().keySet().stream()) .max(Integer::compare).orElse(null); if (maxGroupIdx == null) { return; } acList.addAll(pivot.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey)) .flatMap(e -> { return IntStream.range(0, maxGroupIdx + 1).boxed().map(groupIdx -> { Double chUpDepth = groupIdx * groupThicknessF; Double chLowDepth = (groupIdx + 1) * groupThicknessF; Double sa = e.getValue().get(groupIdx); if (sa == null) { sa = 0d; } String res = null; if (withZeros || sa > 0d) { DistanceBO d = f.getDistanceBO(); String log = Conversion.formatDoubletoDecimalString(d.getLog_start(), "0.0"); LocalDateTime sdt = LocalDateTime .ofInstant(d.getStart_time().toInstant(), ZoneOffset.UTC); String month = StringUtils.leftPad(sdt.getMonthValue() + "", 2, "0"); String day = StringUtils.leftPad(sdt.getDayOfMonth() + "", 2, "0"); //String sas = String.format(Locale.UK, "%11.5f", sa); res = Stream .of(d.getNation(), d.getPlatform(), d.getCruise(), log, sdt.getYear(), month, day, e.getKey(), chUpDepth, chLowDepth, sa) .map(o -> o == null ? "" : o.toString()) .collect(Collectors.joining("\t")); } return res; }).filter(s -> s != null); }).collect(Collectors.toList())); } catch (Exception e) { e.printStackTrace(); } }); String fil2 = path + "/" + fileName + "Values.txt"; acList.add(0, Stream.of("Country", "Vessel", "Cruise", "Log", "Year", "Month", "Day", "Species", "ChUppDepth", "ChLowDepth", "SA").collect(Collectors.joining("\t"))); try { Files.write(Paths.get(fil2), acList, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException ex) { Logger.getLogger(PgNapesIO.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.agent.KubernetesV2OnDemandCachingAgent.java
@Override public CacheResult loadData(ProviderCache providerCache) { log.info(getAgentType() + " is starting"); reloadNamespaces();/*w w w .java 2 s .co m*/ Long start = System.currentTimeMillis(); Map<KubernetesKind, List<KubernetesManifest>> primaryResource; try { primaryResource = loadPrimaryResourceList(); } catch (KubectlJobExecutor.NoResourceTypeException e) { log.warn(getAgentType() + ": resource for this caching agent is not supported for this cluster"); return new DefaultCacheResult(new HashMap<>()); } List<String> primaryKeys = primaryResource.values().stream().flatMap(Collection::stream) .map(rs -> objectMapper.convertValue(rs, KubernetesManifest.class)) .map(mf -> Keys.infrastructure(mf, accountName)).collect(Collectors.toList()); List<CacheData> keepInOnDemand = new ArrayList<>(); List<CacheData> evictFromOnDemand = new ArrayList<>(); providerCache.getAll(ON_DEMAND_TYPE, primaryKeys).forEach(cd -> { // can't be a ternary op due to restrictions on non-statement expressions in lambdas if (shouldKeepInOnDemand(start, cd)) { keepInOnDemand.add(cd); } else { evictFromOnDemand.add(cd); } processOnDemandEntry(cd); }); // sort by increasing cache time to ensure newest entries are first keepInOnDemand.sort(Comparator.comparing(a -> ((Long) a.getAttributes().get(CACHE_TIME_KEY)))); // first build the cache result, then decide which entries to overwrite with on demand data CacheResult result = buildCacheResult(primaryResource); Map<String, Collection<CacheData>> cacheResults = result.getCacheResults(); for (CacheData onDemandData : keepInOnDemand) { String onDemandKey = onDemandData.getId(); log.info("On demand entry '{}' is overwriting load data entry", onDemandKey); String onDemandResultsJson = (String) onDemandData.getAttributes().get(CACHE_RESULTS_KEY); Map<String, Collection<CacheData>> onDemandResults; try { onDemandResults = objectMapper.readValue(onDemandResultsJson, new TypeReference<Map<String, List<DefaultCacheData>>>() { }); } catch (IOException e) { log.error("Failure parsing stored on demand data for '{}'", onDemandKey, e); continue; } mergeCacheResults(cacheResults, onDemandResults); } cacheResults.put(ON_DEMAND_TYPE, keepInOnDemand); Map<String, Collection<String>> evictionResults = new ImmutableMap.Builder<String, Collection<String>>() .put(ON_DEMAND_TYPE, evictFromOnDemand.stream().map(CacheData::getId).collect(Collectors.toList())) .build(); return new DefaultCacheResult(cacheResults, evictionResults); }
From source file:com.epam.ta.reportportal.core.widget.content.MostFailedTestCasesFilterStrategy.java
/** * Sorting result map from data by counter<br> * <b>WARNING: do not use method somewhere else except here cause complex * map value and top-20 limit</b>//from ww w . j a v a 2s . c o m * * @param map * @return */ @SuppressWarnings("hiding") private static <K, ComplexValue extends Comparable<? super ComplexValue>> LinkedHashMap<K, ComplexValue> sortByValue( Map<K, ComplexValue> map) { List<Map.Entry<K, ComplexValue>> list = new LinkedList<>(map.entrySet()); Collections.sort(list, Comparator.comparing(object -> (object.getValue()))); // Splitter for TOP-20 values included LinkedHashMap<K, ComplexValue> result = new LinkedHashMap<>(); int counter = 0; for (Map.Entry<K, ComplexValue> entry : list) { if (counter < ITEMS_COUNT_VALUE) { result.put(entry.getKey(), entry.getValue()); counter++; } else break; } return result; }
From source file:org.apache.james.mailbox.cassandra.mail.CassandraMessageIdMapper.java
private Stream<SimpleMailboxMessage> findAsStream(List<MessageId> messageIds, FetchType fetchType) { return CompletableFutureUtil .allOf(messageIds.stream()/* ww w .j a va 2 s. c o m*/ .map(messageId -> imapUidDAO.retrieve((CassandraMessageId) messageId, Optional.empty()))) .thenApply(stream -> stream.flatMap(Function.identity())) .thenApply(stream -> stream.collect(Guavate.toImmutableList())) .thenCompose(composedMessageIds -> messageDAO.retrieveMessages(composedMessageIds, fetchType, Optional.empty())) .thenCompose(stream -> CompletableFutureUtil.allOf(stream.map( pair -> mailboxExists(pair.getLeft()).thenApply(b -> Optional.of(pair).filter(any -> b))))) .thenApply(stream -> stream.flatMap(OptionalConverter::toStream)) .thenApply(stream -> stream.map(loadAttachments(fetchType))) .thenCompose(CompletableFutureUtil::allOf).join().map(toMailboxMessages()) .sorted(Comparator.comparing(MailboxMessage::getUid)); }
From source file:org.phoenicis.repository.types.ClasspathRepository.java
private List<CategoryDTO> buildCategories(String typeId, String typeFileName) throws RepositoryException { try {/*from w w w .j a v a 2s. c o m*/ final String categoryScanClassPath = packagePath + "/" + typeFileName; Resource[] resources = resourceResolver.getResources(categoryScanClassPath + "/*"); final List<CategoryDTO> categoryDTOS = new ArrayList<>(); for (Resource resource : resources) { final String fileName = resource.getFilename(); if (!"icon.png".equals(fileName) && !"category.json".equals(fileName)) { final CategoryDTO category = buildCategory(typeId, typeFileName, fileName); if (!category.getApplications().isEmpty()) { categoryDTOS.add(category); } } } categoryDTOS.sort(Comparator.comparing(CategoryDTO::getName)); return categoryDTOS; } catch (IOException e) { throw new RepositoryException("Could not build categories", e); } }