List of usage examples for java.util Comparator reverseOrder
public static <T extends Comparable<? super T>> Comparator<T> reverseOrder()
From source file:com.speedment.examples.social.JSONImage.java
public static List<JSONImage> parseFrom(String json) { final JSONObject container = (JSONObject) JSONValue.parse(json); final JSONArray array = (JSONArray) container.get("images"); final List<JSONImage> images = new ArrayList<>(); array.stream().forEach(o -> {//from ww w. j a v a 2 s. co m final JSONObject obj = (JSONObject) o; final JSONImage img = new JSONImage(); final long time = Long.parseLong(obj.get("uploaded").toString()); final LocalDateTime ldt = LocalDateTime.ofEpochSecond(time / 1000L, (int) (time % 1000) * 1000, ZoneOffset.UTC); img.title = obj.get("title").toString(); img.description = obj.get("description").toString(); img.uploaded = ldt; img.uploader = JSONUser.parse((JSONObject) obj.get("uploader")); img.image = fromBase64(obj.get("img_data").toString()); images.add(img); }); Collections.sort(images, Comparator.reverseOrder()); return images; }
From source file:pt.ist.fenix.ui.spring.ChannelsController.java
@RequestMapping public String bookmarks(Model model, @RequestParam(required = false) ExecutionSemester semester, @RequestParam(required = false) ExecutionDegree degree) { model.addAttribute("executions", Bennu.getInstance().getExecutionPeriodsSet().stream() .sorted(Comparator.reverseOrder()).collect(Collectors.toList())); if (semester != null) { model.addAttribute("selectedSemester", semester); model.addAttribute("degrees", semester.getExecutionYear().getExecutionDegreesSortedByDegreeName()); }/* www . j a v a 2s . c om*/ if (semester != null && degree != null) { model.addAttribute("selectedDegree", degree); model.addAttribute("courses", semester.getAssociatedExecutionCoursesSet().stream() .filter(course -> isExecutionCourseForExecutionDegree(course, degree)) .sorted(ExecutionCourse.EXECUTION_COURSE_NAME_COMPARATOR).collect(Collectors.toList())); } model.addAttribute("bookmarks", Authenticate.getUser().getBookmarksSet()); model.addAttribute("slugs", ImmutableSet.of("announcement", "summary")); return "fenix-learning/channels"; }
From source file:org.fenixedu.start.service.APISyncService.java
public Map<String, List<Version>> syncVersions() { logger.info("Synchronizing with the Github API"); Map<String, List<Version>> versions = new HashMap<>(); for (String project : Arrays.asList("bennu", "bennu-spring", "fenixedu-maven")) { try {// w ww. j av a 2s .c o m ResponseEntity<String> resp = new RestTemplate() .getForEntity("https://api.github.com/repos/FenixEdu/" + project + "/tags", String.class); JsonArray array = new JsonParser().parse(resp.getBody()).getAsJsonArray(); List<Version> ownVersions = new ArrayList<>(); versions.put(project, ownVersions); for (JsonElement element : array) { ownVersions .add(Version.parse(element.getAsJsonObject().get("name").getAsString().substring(1))); } ownVersions.sort(Comparator.reverseOrder()); } catch (ResourceAccessException e) { logger.warn("Could not determine versions for {} due to an exception: {}", project, e); } } return versions; }
From source file:org.talend.dataprep.util.SortAndOrderHelper.java
/** * Return the string comparator to use for the given order name. * * @param orderKey the name of the order to apply. * @return the string comparator to use for the given order name. *//*w w w .j a v a 2 s . co m*/ private static Comparator<String> getOrderComparator(String orderKey) { final Comparator<String> comparisonOrder; // Select order (asc or desc) final Order order; try { order = Order.valueOf(orderKey.toUpperCase()); } catch (IllegalArgumentException e) { throw new TDPException(CommonErrorCodes.ILLEGAL_ORDER_FOR_LIST, build().put("order", orderKey)); } switch (order) { case ASC: comparisonOrder = Comparator.naturalOrder(); break; case DESC: comparisonOrder = Comparator.reverseOrder(); break; default: // this should not happen throw new TDPException(CommonErrorCodes.ILLEGAL_ORDER_FOR_LIST, build().put("order", orderKey)); } return comparisonOrder; }
From source file:org.opendatakit.briefcase.reused.UncheckedFiles.java
public static void deleteRecursive(Path path) { walk(path).filter(Files::isRegularFile).forEach(UncheckedFiles::delete); walk(path).filter(p -> !Files.isRegularFile(p)).sorted(Comparator.reverseOrder()) .forEach(UncheckedFiles::delete); }
From source file:fi.helsinki.opintoni.service.UserNotificationService.java
public List<UserNotificationDto> getUserNotifications(Long userId, Optional<String> studentNumber, Optional<String> teacherNumber, Locale locale) { Set<CourseDto> courseDtos = courseService.getCourses(studentNumber, teacherNumber, locale); Set<String> readNotificationIds = userNotificationTransactionalService.findReadNotificationIds(userId); return getUserNotificationDtos(courseDtos, readNotificationIds, locale).stream() .sorted(Comparator.reverseOrder()).collect(Collectors.toList()); }
From source file:org.openstreetmap.josm.gui.preferences.imagery.CacheContentsPanel.java
public static String[][] getCacheStats(CacheAccess<String, BufferedImageCacheEntry> cache) { Set<String> keySet = cache.getCacheControl().getKeySet(); Map<String, int[]> temp = new ConcurrentHashMap<>(); // use int[] as a Object reference to int, gives better performance for (String key : keySet) { String[] keyParts = key.split(":", 2); if (keyParts.length == 2) { int[] counter = temp.get(keyParts[0]); if (counter == null) { temp.put(keyParts[0], new int[] { 1 }); } else { counter[0]++;//from w w w .ja v a2s . co m } } else { Logging.warn("Could not parse the key: {0}. No colon found", key); } } List<Pair<String, Integer>> sortedStats = new ArrayList<>(); for (Entry<String, int[]> e : temp.entrySet()) { sortedStats.add(new Pair<>(e.getKey(), e.getValue()[0])); } sortedStats.sort(Comparator.comparing(o -> o.b, Comparator.reverseOrder())); String[][] ret = new String[sortedStats.size()][3]; int index = 0; for (Pair<String, Integer> e : sortedStats) { ret[index] = new String[] { e.a, e.b.toString(), tr("Clear") }; index++; } return ret; }
From source file:org.jhk.pulsing.web.service.prod.helper.PulseServiceUtil.java
public static Map<Long, String> processTrendingPulseSubscribe(Set<String> tps, ObjectMapper objMapper) { @SuppressWarnings("unchecked") Map<Long, String> tpSubscriptions = Collections.EMPTY_MAP; final Map<String, Integer> count = new HashMap<>(); tps.parallelStream().forEach(tpsIdValueCounts -> { try {/*from w w w. ja v a2 s . c o m*/ _LOGGER.debug( "PulseServiceUtil.processTrendingPulseSubscribe: trying to convert " + tpsIdValueCounts); Map<String, Integer> converted = objMapper.readValue(tpsIdValueCounts, _TRENDING_PULSE_SUBSCRIPTION_TYPE_REF); _LOGGER.debug("PulseServiceUtil.processTrendingPulseSubscribe: sucessfully converted " + converted.size()); //Structure is <id>0x07<value>0x13<timestamp> -> count; i.e. {"10020x07Mocked 10020x13<timestamp>" -> 1} //Need to split the String content, gather the count for the searched interval //and return the sorted using Java8 stream //TODO impl better Map<String, Integer> computed = converted.entrySet().stream().reduce(new HashMap<String, Integer>(), (Map<String, Integer> mapped, Entry<String, Integer> entry) -> { String[] split = entry.getKey() .split(CommonConstants.TIME_INTERVAL_PERSIST_TIMESTAMP_DELIM); Integer value = entry.getValue(); mapped.compute(split[0], (key, val) -> { return val == null ? value : val + value; }); return mapped; }, (Map<String, Integer> result, Map<String, Integer> aggregated) -> { result.putAll(aggregated); return result; }); computed.entrySet().parallelStream().forEach(entry -> { Integer value = entry.getValue(); count.compute(entry.getKey(), (key, val) -> { return val == null ? value : val + value; }); }); } catch (Exception cException) { cException.printStackTrace(); } }); if (count.size() > 0) { tpSubscriptions = count.entrySet().stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .collect(Collectors.toMap( entry -> Long.parseLong( entry.getKey().split(CommonConstants.TIME_INTERVAL_ID_VALUE_DELIM)[0]), entry -> entry.getKey().split(CommonConstants.TIME_INTERVAL_ID_VALUE_DELIM)[1], (x, y) -> { throw new AssertionError(); }, LinkedHashMap::new)); } return tpSubscriptions; }
From source file:internal.static_util.scorer.TermRelatednessScorer.java
/** * Given a word and a set of its related relatedTerms, returns an ordered list of relatedTerms ranked from most relevant to least. * * @param original The word you want to find ranked relatedTerms for * @param relatedTerms The set of terms related to the original * @param minRelevanceRatio An optional parameter for the minimum a synonym must score to be returned. If none * given, .50 is assumed. * @return A list of scoredTerms, in descending order of their scores. *//*from www . ja v a 2 s . co m*/ public static List<ScoredTerm> getRankedTermsWithScores(String original, Set<String> relatedTerms, double minRelevanceRatio) { // Handle null/empty cases if (original == null || relatedTerms == null || relatedTerms.isEmpty()) { return Collections.EMPTY_LIST; } // A HashMap with the word as the key, and its corresponding score List<ScoredTerm> scoredTerms = Collections.synchronizedList(new ArrayList<>()); // Open up a parallel stream on the relatedTerms to perform the doc search on them all relatedTerms.parallelStream().forEach(term -> scoredTerms.add(new ScoredTerm(term, score(original, term)))); // TODO: NOTICE: if the change is made to use a 'top ten' type, refactor to just take first 'x' relatedTerms // Trim the fat - anything below relevance rank gets the D List<ScoredTerm> relevantTerms = getRelevantTerms(scoredTerms, minRelevanceRatio); // Use common.data.ScoredTerm's built-in comparator for sorting purposes // It is by default in ascending order; we want most relevant first, so reverse it Collections.sort(relevantTerms, Comparator.reverseOrder()); // If there were no relevant relatedTerms, return null. // TODO: throw a NoRelevantTerms exception? return relevantTerms.size() > 0 ? relevantTerms : Collections.EMPTY_LIST; }
From source file:org.ballerinalang.composer.service.workspace.local.LocalFSWorkspace.java
@Override public void delete(String path, String type) throws IOException { Path ioPath = Paths.get(path); if (FOLDER_TYPE.equals(type)) { Files.walk(ioPath, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()).map(Path::toFile) .forEach(File::delete); } else {/* w w w . ja v a 2 s . c o m*/ Files.delete(ioPath); } }