下面列出了java.util.List#sort ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Add those {@link ValueProvider ValueProviders} to the valueprovider list that were not used so far by this
* connection. These need to be configurable in editmode and therefore exist in the list. They will be added in
* alphabetical order.
*/
private void setupOtherValueProviders() {
String filter;
try {
filter = (location.getRepository() instanceof RemoteRepository || location.getRepository() instanceof NewVersionedRepository) ? ValueProviderHandlerRegistry.REMOTE : null;
} catch (RepositoryException e) {
filter = ValueProviderHandlerRegistry.REMOTE;
}
final List<ValueProviderModel> newValueProviders = ValueProviderHandlerRegistry.getInstance().getVisibleTypes(filter)
.stream().filter(aType -> this.valueProviders.stream().noneMatch(vp -> aType.equals(vp.getType())))
.map(type -> ValueProviderHandlerRegistry.getInstance().getHandler(type).createNewProvider(ConnectionI18N.getValueProviderTypeName(type)))
.map(ValueProviderModelConverter::toModel).collect(Collectors.toList());
if (newValueProviders.isEmpty()) {
return;
}
newValueProviders.sort(Comparator.comparing(ValueProviderModel::getName));
valueProviders.addAll(newValueProviders);
}
public static List<Country> getAllCountries() {
final Set<Country> allCountries = new HashSet<>();
for (final Locale locale : getAllCountryLocales()) {
String regionCode = getRegionCode(locale.getCountry());
final Region region = new Region(regionCode, getRegionName(regionCode));
Country country = new Country(locale.getCountry(), locale.getDisplayCountry(), region);
if (locale.getCountry().equals("XK"))
country = new Country(locale.getCountry(), "Republic of Kosovo", region);
allCountries.add(country);
}
allCountries.add(new Country("GE", "Georgia", new Region("AS", getRegionName("AS"))));
allCountries.add(new Country("BW", "Botswana", new Region("AF", getRegionName("AF"))));
allCountries.add(new Country("IR", "Iran", new Region("AS", getRegionName("AS"))));
final List<Country> allCountriesList = new ArrayList<>(allCountries);
allCountriesList.sort((locale1, locale2) -> locale1.name.compareTo(locale2.name));
return allCountriesList;
}
@Override
public void onEventTime(InternalTimer<RowData, VoidNamespace> timer) throws Exception {
long timestamp = timer.getTimestamp();
// gets all rows for the triggering timestamps
List<RowData> inputs = dataState.get(timestamp);
if (inputs != null) {
// sort rows on secondary fields if necessary
if (comparator != null) {
inputs.sort(comparator);
}
// emit rows in order
inputs.forEach((RowData row) -> collector.collect(row));
// remove emitted rows from state
dataState.remove(timestamp);
lastTriggeringTsState.update(timestamp);
}
}
/**
* Returns raw top-left and top-right corners
*
* @return list of corners: index 0 - top left, index 1 - top right
*/
public static List<double[]> extractTopCornersFromBoundingBoxes(double[] xCorners, double[] yCorners) {
List<Translation2d> corners = new ArrayList<>();
for (int i = 0; i < xCorners.length; i++) {
corners.add(new Translation2d(xCorners[i], yCorners[i]));
}
corners.sort(xSort);
List<Translation2d> left = corners.subList(0, 4);
List<Translation2d> right = corners.subList(4, 8);
left.sort(ySort);
right.sort(ySort);
List<Translation2d> leftTop = left.subList(0, 2);
List<Translation2d> rightTop = right.subList(0, 2);
leftTop.sort(xSort);
rightTop.sort(xSort);
Translation2d leftCorner = leftTop.get(0);
Translation2d rightCorner = rightTop.get(1);
return List.of(new double[]{leftCorner.x(), leftCorner.y()}, new double[]{rightCorner.x(), rightCorner.y()});
}
@RequestMapping(value = "/selectAgentCount", method = RequestMethod.GET, params = {"from", "to"})
@ResponseBody
public List<AgentCountStatistics> selectAgentCount(@RequestParam("from") long from, @RequestParam("to") long to) {
Range range = Range.newRange(DateTimeUtils.timestampToStartOfDay(from), DateTimeUtils.timestampToStartOfDay(to));
List<AgentCountStatistics> agentCountStatisticsList = agentStatisticsService.selectAgentCount(range);
agentCountStatisticsList.sort(new Comparator<AgentCountStatistics>() {
@Override
public int compare(AgentCountStatistics o1, AgentCountStatistics o2) {
if (o1.getTimestamp() > o2.getTimestamp()) {
return -1;
} else {
return 1;
}
}
});
return agentCountStatisticsList;
}
private List<T> runSorter( Query query, List<T> objects )
{
List<T> sorted = new ArrayList<>( objects );
sorted.sort( ( o1, o2 ) ->
{
for ( Order order : query.getOrders() )
{
int result = order.compare( o1, o2 );
if ( result != 0 ) return result;
}
return 0;
} );
return sorted;
}
protected void sortTimeBasedClickStatResult(List<TimeBasedClickStatRow> returnList) {
returnList.sort((item1, item2) -> {
int cmp = item1.getClickTime().compareTo(item2.getClickTime());
if (cmp == 0) {
if (item1.getDeviceClass() == item2.getDeviceClass()) {
cmp = Integer.compare(item1.getColumn_index(), item2.getColumn_index());
} else if (item1.getDeviceClass() == null) {
cmp = 1;
} else if (item2.getDeviceClass() == null) {
cmp = -1;
} else {
cmp = item1.getDeviceClass().compareTo(item2.getDeviceClass());
}
}
return cmp;
});
}
public List<Message> getMessages() {
if (root.errors == null) {
return Collections.emptyList();
}
List<Message> result = new ArrayList<>(root.errors);
result.sort(new Comparator<Message>() {
@Override
public int compare(Message a, Message b) {
return a.getSource().compareTo(b.getSource());
}
});
return unmodifiableList(result);
}
private void orderByChildElement(final List<Element> toSort, final String childTagName) {
toSort.sort((a, b) -> {
final String valueA = DomUtils.getChildText(a, childTagName);
final String valueB = DomUtils.getChildText(b, childTagName );
return valueA.compareTo(valueB);
});
}
private void sort(LinkedHashMap<ID, NodeInfo<ID, N>> nodes, List<NodeInfo<ID, N>> results) {
while (!nodes.isEmpty()) {
NodeInfo<ID, N> curr = removeFirstIndependent(nodes);
if (curr != null) {
// yay, simple. Just add the found independent node to the results.
results.add(curr);
} else {
// ok, there is a cycle in the graph. Let's remove all the nodes in the first cycle we find
// from our predecessors map, add them to the result in their original order and try to
// continue normally
// find the first cycle in the predecessors (in the original list order)
Iterator<NodeInfo<ID, N>> nexts = nodes.values().iterator();
List<NodeInfo<ID, N>> cycle;
do {
curr = nexts.next();
cycle = findCycle(curr, nodes);
} while (cycle.isEmpty() && nexts.hasNext());
// If we ever find a graph that doesn't have any independent node, yet we fail to find a
// cycle in it, the universe must be broken.
if (cycle.isEmpty()) {
throw new IllegalStateException(
String.format(
"Failed to find a cycle in a graph that doesn't seem to have any independent"
+ " node. This should never happen. Please file a bug. Current state of the"
+ " sorting is: nodes=%s, results=%s",
nodes.toString(), results.toString()));
}
cycle.sort(Comparator.comparingInt(a -> a.sourcePosition));
for (NodeInfo<ID, N> n : cycle) {
removePredecessorMapping(nodes, n);
results.add(n);
}
}
}
}
/**
* Sort all molecular formulas by score of ppm distance, isotope sccore and msms score (with
* weighting). Best will be at first position
*
* @param list
* @param neutralMass
* @param ppmMax
* @param weightIsotopeScore
* @param weightMSMSscore
*/
public static void sortFormulaList(List<MolecularFormulaIdentity> list, double neutralMass,
double ppmMax, double weightIsotopeScore, double weightMSMSscore) {
if (list == null)
return;
list.sort(new Comparator<MolecularFormulaIdentity>() {
@Override
public int compare(MolecularFormulaIdentity a, MolecularFormulaIdentity b) {
double scoreA = a.getScore(neutralMass, ppmMax, weightIsotopeScore, weightMSMSscore);
double scoreB = b.getScore(neutralMass, ppmMax, weightIsotopeScore, weightMSMSscore);
// best to position 0 (therefore change A B)
return Double.compare(scoreB, scoreA);
}
});
}
@Override
public <T> RevisionUpdate<T> updateRevision(final RevisionClaim originalClaim, final UpdateRevisionTask<T> task) throws ExpiredRevisionClaimException {
logger.debug("Attempting to update revision using {}", originalClaim);
final List<Revision> revisionList = new ArrayList<>(originalClaim.getRevisions());
revisionList.sort(new RevisionComparator());
for (final Revision revision : revisionList) {
final Revision currentRevision = getRevision(revision.getEntityId());
final boolean verified = revision.equals(currentRevision);
if (!verified) {
// Throw an Exception indicating that we failed to obtain the locks
throw new InvalidRevisionException("Invalid Revision was given for entity with ID '" + revision.getEntityId() + "'");
}
}
// We successfully verified all revisions.
logger.debug("Successfully verified Revision Claim for all revisions");
// Perform the update
final RevisionUpdate<T> updatedComponent = task.update();
// If the update succeeded then put the updated revisions into the revisionMap
// If an exception is thrown during the update we don't want to update revision so it is ok to bounce out of this method
if (updatedComponent != null) {
for (final Revision updatedRevision : updatedComponent.getUpdatedRevisions()) {
revisionMap.put(updatedRevision.getEntityId(), updatedRevision);
}
}
return updatedComponent;
}
@Test(dataProvider = "examples")
public void testFindStrobogrammatic(int n, List<String> expected) {
StrobogrammaticNumber2 s = new StrobogrammaticNumber2();
List<String> actual = new ArrayList<>(s.findStrobogrammatic(n));
List<String> sortedExpected = new ArrayList<>(expected);
actual.sort(Comparator.comparingInt(Integer::parseInt));
sortedExpected.sort(Comparator.comparingInt(Integer::parseInt));
Assert.assertEquals(actual, sortedExpected);
}
public List<String> namesOfAllVariablesInScope() {
List<String> result = new ArrayList<>();
Scope scope = this;
while (scope != null) {
result.addAll(scope.keys());
scope = scope.parent;
}
result.sort(String::compareTo);
return Collections.unmodifiableList(result);
}
/**
* Gets all method names from the given service descriptor.
*
* @param serviceDescriptor The service descriptor to get the names from.
* @return The newly created and sorted list of the method names.
*/
protected List<String> collectMethodNamesForService(final ServiceDescriptor serviceDescriptor) {
final List<String> methods = new ArrayList<>();
for (final MethodDescriptor<?, ?> grpcMethod : serviceDescriptor.getMethods()) {
methods.add(extractMethodName(grpcMethod));
}
methods.sort(String.CASE_INSENSITIVE_ORDER);
return methods;
}
private void writeSchedulingMetrics(ClientSideMetrics clientSideMetrics) {
this.writeBeforeSchedulingMetrics();
List<ImmutablePair<String, SchedulingTimeSpan>> partitionSchedulingTimeSpans = clientSideMetrics.getPartitionSchedulingTimeSpans();
partitionSchedulingTimeSpans.sort((o1, o2) -> (int) (o2.right.getResponseTime() - o1.right.getResponseTime()));
for (ImmutablePair<String, SchedulingTimeSpan> partitionSchedulingDuration :
partitionSchedulingTimeSpans) {
String partitionId = partitionSchedulingDuration.getLeft();
SchedulingTimeSpan schedulingDuration = partitionSchedulingDuration.getRight();
this.writePartitionSchedulingDuration(partitionId, schedulingDuration);
}
this.writeAfterSchedulingMetrics();
}
/** {@inheritDoc} */
@Override public void processDump(ThreadPageLocksDumpLock snapshot) {
sb.append("Page locks dump:").append(U.nl()).append(U.nl());
List<ThreadState> threadStates = new ArrayList<>(snapshot.threadStates);
// Sort thread dump by thread names.
threadStates.sort(new Comparator<ThreadState>() {
/** {@inheritDoc} */
@Override public int compare(ThreadState thState1, ThreadState thState2) {
return thState1.threadName.compareTo(thState2.threadName);
}
});
for (ThreadState ths : threadStates) {
sb.append("Thread=[name=").append(ths.threadName)
.append(", id=").append(ths.threadId)
.append("], state=").append(ths.state)
.append(U.nl());
PageLockDump pageLockDump0;
if (ths.invalidContext == null)
pageLockDump0 = ths.pageLockDump;
else {
sb.append(ths.invalidContext.msg).append(U.nl());
pageLockDump0 = ths.invalidContext.dump;
}
pageLockDump0.apply(this);
sb.append(U.nl());
}
}
@Test
public void sortDates() {
LocalDate ld1 = LocalDate.of(2019, 3, 1);
LocalDate ld2 = LocalDate.of(2019, 1, 1);
LocalDate ld3 = LocalDate.of(2019, 2, 1);
List<LocalDate> dates = new ArrayList<>(List.of(ld1, ld2, ld3));
dates.sort(Comparator.naturalOrder());
assertThat(dates).containsExactly(ld2, ld3, ld1);
dates.sort(Comparator.reverseOrder());
assertThat(dates).containsExactly(ld1, ld3, ld2);
}
@Override
public <T extends Storable> Collection<T> find(final String namespace,
final List<QueryParam> queryParams,
final List<OrderByField> orderByFields) throws StorageException {
List<T> storables = new ArrayList<>();
if (queryParams == null) {
Collection<T> collection = list(namespace);
storables = Lists.newArrayList(collection);
} else {
Class<?> clazz = nameSpaceClassMap.get(namespace);
if (clazz != null) {
Map<PrimaryKey, Storable> storableMap = storageMap.get(namespace);
if (storableMap != null) {
for (Storable val : storableMap.values()) {
if (matches(val, queryParams, clazz)) {
storables.add((T) val);
}
}
}
}
}
if (orderByFields != null && !orderByFields.isEmpty()) {
storables.sort((storable1, storable2) -> {
try {
for (OrderByField orderByField : orderByFields) {
Comparable value1 = ReflectionHelper.invokeGetter(orderByField.getFieldName(), storable1);
Comparable value2 = ReflectionHelper.invokeGetter(orderByField.getFieldName(), storable2);
int compareTo;
// same values continue
if(value1 == value2) {
continue;
} else if(value1 == null) {
// value2 is non null
compareTo = -1;
} else if(value2 == null) {
// value1 is non null
compareTo = 1;
} else {
// both value and value2 non null
compareTo = value1.compareTo(value2);
}
if (compareTo == 0) {
continue;
}
return orderByField.isDescending() ? -compareTo : compareTo;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
// all group by fields are matched means equal
return 0;
});
}
return storables;
}
@Test
public void test_PDI17117() throws Exception {
final String virtualFile = createVirtualFile( "pdi-14832.txt", "1,\n" );
BaseFileField col2 = field( "col2" );
col2.setIfNullValue( "DEFAULT" );
TextFileInputMeta meta = createMetaObject( field( "col1" ), col2 );
meta.inputFiles.passingThruFields = true;
meta.inputFiles.acceptingFilenames = true;
TextFileInputData data = createDataObject( virtualFile, ",", "col1", "col2" );
TextFileInput input = Mockito.spy( StepMockUtil.getStep( TextFileInput.class, TextFileInputMeta.class, "test" ) );
RowSet rowset = Mockito.mock( RowSet.class );
RowMetaInterface rwi = Mockito.mock( RowMetaInterface.class );
Object[] obj1 = new Object[2];
Object[] obj2 = new Object[2];
Mockito.doReturn( rowset ).when( input ).findInputRowSet( null );
Mockito.doReturn( null ).when( input ).getRowFrom( rowset );
Mockito.when( input.getRowFrom( rowset ) ).thenReturn( obj1, obj2, null );
Mockito.doReturn( rwi ).when( rowset ).getRowMeta();
Mockito.when( rwi.getString( obj2, 0 ) ).thenReturn( "filename1", "filename2" );
List<Object[]> output = TransTestingUtil.execute( input, meta, data, 0, false );
List<String> passThroughKeys = new ArrayList<>( data.passThruFields.keySet() );
Assert.assertNotNull( passThroughKeys );
// set order is not guaranteed - order alphabetically
passThroughKeys.sort( String.CASE_INSENSITIVE_ORDER );
assertEquals( 2, passThroughKeys.size() );
Assert.assertNotNull( passThroughKeys.get( 0 ) );
Assert.assertTrue( passThroughKeys.get( 0 ).startsWith( "0_file" ) );
Assert.assertTrue( passThroughKeys.get( 0 ).endsWith( "filename1" ) );
Assert.assertNotNull( passThroughKeys.get( 1 ) );
Assert.assertTrue( passThroughKeys.get( 1 ).startsWith( "1_file" ) );
Assert.assertTrue( passThroughKeys.get( 1 ).endsWith( "filename2" ) );
deleteVfsFile( virtualFile );
}