List of usage examples for java.util List sort
@SuppressWarnings({ "unchecked", "rawtypes" }) default void sort(Comparator<? super E> c)
From source file:de.dkfz.roddy.client.fxuiclient.RoddyUIController.java
/** * Load a list of available projects related to the current ini file * Load all projects from accessible configuration files. * This is done in a JavaFX Task./*from w ww.j ava 2 s . co m*/ * * @param iniFile */ private void loadProjects(File iniFile) { RoddyUITask task = new RoddyUITask<TreeItem<FXICCWrapper>>(UIConstants.UITASK_LOAD_PROJECTS) { @Override public TreeItem<FXICCWrapper> _call() throws Exception { TreeItem<FXICCWrapper> root = new TreeItem<>(null); AppConfig appConfig = new AppConfig(iniFile); String[] allConfigDirectories = appConfig.getProperty("configurationDirectories", "") .split(StringConstants.SPLIT_COMMA); List<File> folders = new LinkedList<>(); for (String s : allConfigDirectories) { File f = new File(s); if (f.exists()) folders.add(f); } ConfigurationFactory.initialize(folders); List<InformationalConfigurationContent> availableProjectConfigurations = ConfigurationFactory .getInstance().getAvailableProjectConfigurations(); availableProjectConfigurations.sort(new Comparator<InformationalConfigurationContent>() { @Override public int compare(InformationalConfigurationContent o1, InformationalConfigurationContent o2) { return o1.name.compareTo(o2.name); } }); loadProjectsRecursivelyFromXMLFiles(root, availableProjectConfigurations); return root; } @Override public void _failed() { logger.log(Level.WARNING, UIConstants.ERRTXT_PROJECTSNOTLOADED, getException()); } @Override protected void _succeeded() { allProjectTreeItemsRoot = valueProperty().get(); refreshProjectView(null); } }; RoddyUITask.runTask(task); }
From source file:com.baidu.rigel.biplatform.tesseract.isservice.index.service.impl.IndexMetaServiceImpl.java
/** * //from w ww .j a va 2 s .c o m * ?? * * @param idxMetaList * ? * @return List<IndexShard> */ private List<IndexShard> getIndexShardListFromIndexMetaListOrderbyShardId(List<IndexMeta> idxMetaList) { List<IndexShard> result = new ArrayList<IndexShard>(); if (idxMetaList != null && idxMetaList.size() != 0) { for (IndexMeta idxMeta : idxMetaList) { result.addAll(idxMeta.getIdxShardList()); } } result.sort((o1, o2) -> { if (o1 != null && o2 != null && o1.getShardId() != null && o2.getShardId() != null) { return o1.getShardId().compareTo(o2.getShardId()); } else if (o1 != null && o2 != null && o1.getShardId() != null && o2.getShardId() == null) { return 1; } else if (o1 != null && o2 != null && o1.getShardId() == null && o2.getShardId() != null) { return -1; } else if (o1 == null || o2 == null) { return 0; } return 0; }); return result; }
From source file:org.zanata.action.ProjectHome.java
public List<HAccountRole> getAvailableRoles() { List<HAccountRole> allRoles = accountRoleDAO.findAll(); allRoles.sort(ComparatorUtil.ACCOUNT_ROLE_COMPARATOR); return allRoles; }
From source file:org.niord.core.message.MessageService.java
/** Returns a single message from the list - preferably from the current domain */ private Message resolveMessage(List<Message> messages) { // Sort messages by domain and status messages.sort(new MessageIdMatchComparator(domainService.currentDomain())); // No current domain - just return the first message return messages.get(0); }
From source file:org.apache.flink.table.codegen.SortCodeGeneratorTest.java
private void testInner() throws Exception { List<MemorySegment> segments = new ArrayList<>(); for (int i = 0; i < 100; i++) { segments.add(MemorySegmentFactory.wrap(new byte[32768])); }//from ww w .j a v a 2 s. c o m InternalType[] fieldTypes = getFieldTypes(); InternalType[] keyTypes = getKeyTypes(); Tuple2<NormalizedKeyComputer, RecordComparator> tuple2 = getSortBaseWithNulls( this.getClass().getSimpleName(), keyTypes, keys, orders, nullsIsLast); BinaryRowSerializer serializer = new BinaryRowSerializer(fieldTypes.length); BinaryInMemorySortBuffer sortBuffer = BinaryInMemorySortBuffer.createBuffer(tuple2.f0, (AbstractRowSerializer) serializer, serializer, tuple2.f1, segments); BinaryRow[] dataArray = getTestData(); List<BinaryRow> data = Arrays.asList(dataArray.clone()); List<BinaryRow> binaryRows = Arrays.asList(dataArray.clone()); Collections.shuffle(binaryRows); for (BinaryRow row : binaryRows) { if (!sortBuffer.write(row)) { throw new RuntimeException(); } } new QuickSort().sort(sortBuffer); MutableObjectIterator<BinaryRow> iter = sortBuffer.getIterator(); List<BinaryRow> result = new ArrayList<>(); BinaryRow row = serializer.createInstance(); while ((row = iter.next(row)) != null) { result.add(row.copy()); } data.sort((o1, o2) -> { for (int i = 0; i < keys.length; i++) { InternalType t = types[fields[keys[i]]]; boolean order = orders[i]; Object first = null; Object second = null; if (!o1.isNullAt(keys[i])) { first = TypeGetterSetters.get(o1, keys[i], keyTypes[i]); } if (!o2.isNullAt(keys[i])) { second = TypeGetterSetters.get(o2, keys[i], keyTypes[i]); } if (first == null && second == null) { } else if (first == null) { return order ? -1 : 1; } else if (second == null) { return order ? 1 : -1; } else if (first instanceof Comparable) { int ret = ((Comparable) first).compareTo(second); if (ret != 0) { return order ? ret : -ret; } } else if (t instanceof ArrayType) { BinaryArray leftArray = (BinaryArray) first; BinaryArray rightArray = (BinaryArray) second; int minLength = Math.min(leftArray.numElements(), rightArray.numElements()); for (int j = 0; j < minLength; j++) { boolean isNullLeft = leftArray.isNullAt(j); boolean isNullRight = rightArray.isNullAt(j); if (isNullLeft && isNullRight) { // Do nothing. } else if (isNullLeft) { return order ? -1 : 1; } else if (isNullRight) { return order ? 1 : -1; } else { int comp = Byte.compare(leftArray.getByte(j), rightArray.getByte(j)); if (comp != 0) { return order ? comp : -comp; } } } if (leftArray.numElements() < rightArray.numElements()) { return order ? -1 : 1; } else if (leftArray.numElements() > rightArray.numElements()) { return order ? 1 : -1; } } else if (t.equals(InternalTypes.BINARY)) { int comp = org.apache.flink.table.runtime.sort.SortUtil.compareBinary((byte[]) first, (byte[]) second); if (comp != 0) { return order ? comp : -comp; } } else if (t instanceof RowType) { RowType rowType = (RowType) t; int comp; if (rowType.getTypeAt(0).equals(InternalTypes.INT)) { comp = INT_ROW_COMP.compare(INT_ROW_CONV.toExternal(first), INT_ROW_CONV.toExternal(second)); } else { comp = NEST_ROW_COMP.compare(NEST_ROW_CONV.toExternal(first), NEST_ROW_CONV.toExternal(second)); } if (comp != 0) { return order ? comp : -comp; } } else if (t instanceof GenericType) { Integer i1 = BinaryGeneric.getJavaObjectFromBinaryGeneric((BinaryGeneric) first, IntSerializer.INSTANCE); Integer i2 = BinaryGeneric.getJavaObjectFromBinaryGeneric((BinaryGeneric) second, IntSerializer.INSTANCE); int comp = Integer.compare(i1, i2); if (comp != 0) { return order ? comp : -comp; } } else { throw new RuntimeException(); } } return 0; }); StringBuilder builder = new StringBuilder(); for (int i = 0; i < data.size(); i++) { builder.append("\n").append("expect: ").append(data.get(i).toOriginString(fieldTypes)) .append("; actual: ").append(result.get(i).toOriginString(fieldTypes)); } builder.append("\n").append("types: ").append(Arrays.asList(fieldTypes)); builder.append("\n").append("keys: ").append(Arrays.toString(keys)); String msg = builder.toString(); for (int i = 0; i < data.size(); i++) { for (int j = 0; j < keys.length; j++) { boolean isNull1 = data.get(i).isNullAt(keys[j]); boolean isNull2 = result.get(i).isNullAt(keys[j]); Assert.assertEquals(msg, isNull1, isNull2); if (!isNull1 || !isNull2) { Object o1 = TypeGetterSetters.get(data.get(i), keys[j], keyTypes[j]); Object o2 = TypeGetterSetters.get(result.get(i), keys[j], keyTypes[j]); if (keyTypes[j].equals(InternalTypes.BINARY)) { Assert.assertArrayEquals(msg, (byte[]) o1, (byte[]) o2); } else { Assert.assertEquals(msg, o1, o2); } } } } }
From source file:org.springframework.messaging.handler.invocation.reactive.AbstractMethodMessageHandler.java
@Nullable private Match<T> getHandlerMethod(Message<?> message) { List<Match<T>> matches = new ArrayList<>(); RouteMatcher.Route destination = getDestination(message); List<T> mappingsByUrl = destination != null ? this.destinationLookup.get(destination.value()) : null; if (mappingsByUrl != null) { addMatchesToCollection(mappingsByUrl, message, matches); }// w w w.ja va 2 s . c om if (matches.isEmpty()) { // No direct hits, go through all mappings Set<T> allMappings = this.handlerMethods.keySet(); addMatchesToCollection(allMappings, message, matches); } if (matches.isEmpty()) { handleNoMatch(destination, message); return null; } Comparator<Match<T>> comparator = new MatchComparator(getMappingComparator(message)); matches.sort(comparator); if (logger.isTraceEnabled()) { logger.trace("Found " + matches.size() + " handler methods: " + matches); } Match<T> bestMatch = matches.get(0); if (matches.size() > 1) { Match<T> secondBestMatch = matches.get(1); if (comparator.compare(bestMatch, secondBestMatch) == 0) { HandlerMethod m1 = bestMatch.handlerMethod; HandlerMethod m2 = secondBestMatch.handlerMethod; throw new IllegalStateException( "Ambiguous handler methods mapped for destination '" + destination.value() + "': {" + m1.getShortLogMessage() + ", " + m2.getShortLogMessage() + "}"); } } return bestMatch; }
From source file:bwem.map.MapInitializerImpl.java
@Override public List<MutablePair<WalkPosition, MiniTile>> getSortedMiniTilesByDescendingAltitude() { final List<MutablePair<WalkPosition, MiniTile>> miniTilesByDescendingAltitude = new ArrayList<>(); for (int y = 0; y < getData().getMapData().getWalkSize().getY(); ++y) { for (int x = 0; x < getData().getMapData().getWalkSize().getX(); ++x) { final WalkPosition w = new WalkPosition(x, y); final MiniTile miniTile = ((TerrainDataInitializer) getData()).getMiniTile_(w, CheckMode.NO_CHECK); if (((MiniTileImpl) miniTile).isAreaIdMissing()) { miniTilesByDescendingAltitude.add(new MutablePair<>(w, miniTile)); }//from w w w. j ava 2 s . c o m } } miniTilesByDescendingAltitude.sort(new PairGenericMiniTileAltitudeComparator<>()); Collections.reverse(miniTilesByDescendingAltitude); return miniTilesByDescendingAltitude; }
From source file:org.tightblog.service.WeblogManager.java
/** * Get list of WeblogEntryTagAggregate objects for the tags comprising a weblog. * * @param weblog Weblog or null to get for all weblogs. * @param sortBy Sort by either 'name' or 'count' (null for name) * @param startsWith Prefix for tags to be returned (null or a string of length > 0) * @param offset 0-based index into returns * @param limit Max objects to return (or -1 for no limit) * @return List of tags matching the criteria. *//*from w w w . ja v a2 s . c o m*/ public List<WeblogEntryTagAggregate> getTags(Weblog weblog, String sortBy, String startsWith, int offset, int limit) { boolean sortByName = !"count".equals(sortBy); List<Object> params = new ArrayList<>(); int size = 0; StringBuilder queryString = new StringBuilder(); queryString.append("SELECT wtag.name, COUNT(wtag), MIN(we.pubTime), MAX(we.pubTime) " + "FROM WeblogEntryTag wtag, WeblogEntry we WHERE wtag.weblogEntry.id = we.id"); if (weblog != null) { params.add(size++, weblog.getId()); queryString.append(" AND wtag.weblog.id = ?").append(size); } if (startsWith != null && startsWith.length() > 0) { params.add(size++, startsWith + '%'); queryString.append(" AND wtag.name LIKE ?").append(size); } if (sortByName) { sortBy = "wtag.name"; } else { sortBy = "COUNT(wtag) DESC"; } queryString.append(" GROUP BY wtag.name ORDER BY ").append(sortBy); TypedQuery<WeblogEntryTagAggregate> query = entityManager.createQuery(queryString.toString(), WeblogEntryTagAggregate.class); for (int i = 0; i < params.size(); i++) { query.setParameter(i + 1, params.get(i)); } if (offset != 0) { query.setFirstResult(offset); } if (limit != -1) { query.setMaxResults(limit); } List queryResults = query.getResultList(); List<WeblogEntryTagAggregate> results = new ArrayList<>(); if (queryResults != null) { for (Object obj : queryResults) { Object[] row = (Object[]) obj; WeblogEntryTagAggregate ce = new WeblogEntryTagAggregate(); ce.setName((String) row[0]); // The JPA query retrieves SUM(w.total) always as long ce.setTotal(((Long) row[1]).intValue()); if (weblog != null) { ce.setFirstEntry(((Instant) row[2]).atZone(weblog.getZoneId()).toLocalDate()); ce.setLastEntry(((Instant) row[3]).atZone(weblog.getZoneId()).toLocalDate()); } results.add(ce); } } if (sortByName) { results.sort(WeblogEntryTagAggregate.NAME_COMPARATOR); } else { results.sort(WeblogEntryTagAggregate.COUNT_COMPARATOR); } return results; }
From source file:com.evolveum.midpoint.web.component.prism.ObjectWrapperFactory.java
private <O extends ObjectType> List<ContainerWrapper<? extends Containerable>> createContainerWrappers( ObjectWrapper<O> oWrapper, PrismObject<O> object, PrismObjectDefinition<O> objectDefinitionForEditing, ContainerStatus cStatus, Task task, OperationResult pResult) throws SchemaException { OperationResult result = pResult.createSubresult(CREATE_CONTAINERS); List<ContainerWrapper<? extends Containerable>> containerWrappers = new ArrayList<>(); ContainerWrapperFactory cwf = new ContainerWrapperFactory(modelServiceLocator); try {// w w w . j a v a 2s . c o m ContainerWrapper<O> mainContainerWrapper = cwf.createContainerWrapper(object, oWrapper.getStatus(), cStatus, ItemPath.EMPTY_PATH, task); mainContainerWrapper.setDisplayName("prismContainer.mainPanelDisplayName"); result.addSubresult(cwf.getResult()); containerWrappers.add(mainContainerWrapper); addContainerWrappers(containerWrappers, oWrapper, object, null, task, result); } catch (SchemaException | RuntimeException e) { LoggingUtils.logUnexpectedException(LOGGER, "Error occurred during container wrapping" + e.getMessage(), e); result.recordFatalError("Error occurred during container wrapping, reason: " + e.getMessage(), e); throw e; } containerWrappers.sort(new ItemWrapperComparator()); result.recomputeStatus(); result.recordSuccessIfUnknown(); return containerWrappers; }
From source file:com.thoughtworks.go.apiv5.plugininfos.PluginInfosControllerV5.java
public String index(Request request, Response response) throws IOException { List<CombinedPluginInfo> pluginInfos = new ArrayList<>(); String pluginType = request.queryParams("type"); Boolean includeBad = Boolean.valueOf(request.queryParams("include_bad")); if (StringUtils.isNotBlank(pluginType) && !extensionsRegistry.allRegisteredExtensions().contains(pluginType)) { throw new UnprocessableEntityException( String.format("Invalid plugin type '%s'. It has to be one of '%s'.", pluginType, String.join(", ", extensionsRegistry.allRegisteredExtensions()))); }/* ww w . ja v a 2 s. c o m*/ Collection<CombinedPluginInfo> validPluginInfos = this.pluginInfoFinder.allPluginInfos(pluginType).stream() .filter(pluginInfo -> !hasUnsupportedExtensionType(pluginInfo)).collect(Collectors.toList()); pluginInfos.addAll(validPluginInfos); if (includeBad) { List<BadPluginInfo> badPluginInfos = defaultPluginManager.plugins().stream() .filter(GoPluginDescriptor::isInvalid).map(BadPluginInfo::new).collect(toList()); pluginInfos.addAll(badPluginInfos); } pluginInfos .sort(Comparator.comparing((CombinedPluginInfo pluginInfos1) -> pluginInfos1.getDescriptor().id())); String etag = etagFor(pluginInfos); if (fresh(request, etag)) { return notModified(response); } setEtagHeader(response, etag); return writerForTopLevelObject(request, response, writer -> PluginInfosRepresenter.toJSON(writer, pluginInfos)); }