java.util.Collections.sort()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(9.4k)|赞(0)|评价(0)|浏览(200)

本文整理了Java中java.util.Collections.sort()方法的一些代码示例,展示了Collections.sort()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Collections.sort()方法的具体详情如下:
包路径:java.util.Collections
类名称:Collections
方法名:sort

Collections.sort介绍

[英]Sorts the given list in ascending natural order. The algorithm is stable which means equal elements don't get reordered.
[中]按自然升序对给定列表排序。该算法是稳定的,这意味着相等的元素不会被重新排序。

代码示例

canonical example by Tabnine

private void mappingWordsLength(List<String> wordsList) {
 Map<Integer, Set<String>> mapping = new HashMap<>();
 for (String word : wordsList) {
  mapping.computeIfAbsent(word.length(), HashSet::new).add(word);
 }
 List<Integer> lengths = new LinkedList<>(mapping.keySet());
 Collections.sort(lengths);
 lengths.forEach(n -> System.out.println(mapping.get(n).size() + " words with " + n + " chars"));
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Private constructor accepting parsed media type expressions.
 */
private ConsumesRequestCondition(Collection<ConsumeMediaTypeExpression> expressions) {
  this.expressions = new ArrayList<>(expressions);
  Collections.sort(this.expressions);
}

代码示例来源:origin: apache/incubator-dubbo

public static List<String> sortSimpleName(List<String> list) {
  if (list != null && list.size() > 0) {
    Collections.sort(list, SIMPLE_NAME_COMPARATOR);
  }
  return list;
}

代码示例来源:origin: stackoverflow.com

List<String> strings = new ArrayList<String>()
strings.add("lol");
strings.add("cat");

Collections.sort(strings);
for (String s : strings) {
  System.out.println(s);
}
// Prints out "cat" and "lol"

代码示例来源:origin: stackoverflow.com

List<String> keywords = Arrays.asList("Apple", "Ananas", "Mango", "Banana", "Beer"); 
Map<Character, List<String>> result = new HashMap<Character, List<String>>(); 
for(String k : keywords) {   
  char firstChar = k.charAt(0);     
  if(!result.containsKey(firstChar)) {     
    result.put(firstChar, new  ArrayList<String>());   
  }     
  result.get(firstChar).add(k); 
} 
for(List<String> list : result.values()) {   
  Collections.sort(list); 
}
System.out.println(result);

代码示例来源:origin: spring-projects/spring-framework

private List<String> getConverterStrings() {
    List<String> converterStrings = new ArrayList<>();
    for (ConvertersForPair convertersForPair : this.converters.values()) {
      converterStrings.add(convertersForPair.toString());
    }
    Collections.sort(converterStrings);
    return converterStrings;
  }
}

代码示例来源:origin: androidannotations/androidannotations

private void processParam(Element element, T holder) {
  ExecutableElement method = (ExecutableElement) element.getEnclosingElement();
  List<? extends VariableElement> parameters = method.getParameters();
  List<ParamHelper> parameterList = methodParameterMap.get(method);
  JBlock targetBlock = methodBlockMap.get(method);
  int paramCount = parameters.size();
    parameterList = new ArrayList<>();
    methodParameterMap.put(method, parameterList);
    methodBlockMap.put(method, targetBlock);
    VariableElement param = parameters.get(paramIndex);
    if (param.equals(element)) {
      AbstractJClass type = codeModelHelper.typeMirrorToJClass(param.asType());
      parameterList.add(new ParamHelper(fieldRef, paramIndex, param));
  if (parameterList.size() == paramCount) {
    String methodName = method.getSimpleName().toString();
    Collections.sort(parameterList);

代码示例来源:origin: apache/rocketmq

private long calculateOpOffset(List<Long> doneOffset, long oldOffset) {
  Collections.sort(doneOffset);
  long newOffset = oldOffset;
  for (int i = 0; i < doneOffset.size(); i++) {
    if (doneOffset.get(i) == newOffset) {
      newOffset++;
    } else {
      break;
    }
  }
  return newOffset;
}

代码示例来源:origin: apache/kafka

@Override
public Map<String, List<TopicPartition>> assign(Map<String, Integer> partitionsPerTopic,
                        Map<String, Subscription> subscriptions) {
  Map<String, List<String>> consumersPerTopic = consumersPerTopic(subscriptions);
  Map<String, List<TopicPartition>> assignment = new HashMap<>();
  for (String memberId : subscriptions.keySet())
    assignment.put(memberId, new ArrayList<>());
  for (Map.Entry<String, List<String>> topicEntry : consumersPerTopic.entrySet()) {
    String topic = topicEntry.getKey();
    List<String> consumersForTopic = topicEntry.getValue();
    Integer numPartitionsForTopic = partitionsPerTopic.get(topic);
    if (numPartitionsForTopic == null)
      continue;
    Collections.sort(consumersForTopic);
    int numPartitionsPerConsumer = numPartitionsForTopic / consumersForTopic.size();
    int consumersWithExtraPartition = numPartitionsForTopic % consumersForTopic.size();
    List<TopicPartition> partitions = AbstractPartitionAssignor.partitions(topic, numPartitionsForTopic);
    for (int i = 0, n = consumersForTopic.size(); i < n; i++) {
      int start = numPartitionsPerConsumer * i + Math.min(i, consumersWithExtraPartition);
      int length = numPartitionsPerConsumer + (i + 1 > consumersWithExtraPartition ? 0 : 1);
      assignment.get(consumersForTopic.get(i)).addAll(partitions.subList(start, start + length));
    }
  }
  return assignment;
}

代码示例来源:origin: pentaho/pentaho-kettle

/**
 * @return A sorted list of distinct occurrences of the used message package names
 */
public List<String> getMessagesPackagesList( String sourceFolder ) {
 Map<String, List<KeyOccurrence>> packageOccurrences = sourcePackageOccurrences.get( sourceFolder );
 List<String> list = new ArrayList<String>( packageOccurrences.keySet() );
 Collections.sort( list );
 return list;
}

代码示例来源:origin: stackoverflow.com

List<CustomObject> list = new ArrayList<CustomObject>();
Collections.sort(list, (left, right) -> left.getId() - right.getId());
System.out.println(list);

代码示例来源:origin: apache/zookeeper

static void usage() {
  System.err.println("ZooKeeper -server host:port cmd args");
  List<String> cmdList = new ArrayList<String>(commandMap.keySet());
  Collections.sort(cmdList);
  for (String cmd : cmdList) {
    System.err.println("\t"+cmd+ " " + commandMap.get(cmd));
  }
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Return a FlashMap contained in the given list that matches the request.
 * @return a matching FlashMap or {@code null}
 */
@Nullable
private FlashMap getMatchingFlashMap(List<FlashMap> allMaps, HttpServletRequest request) {
  List<FlashMap> result = new LinkedList<>();
  for (FlashMap flashMap : allMaps) {
    if (isFlashMapForRequest(flashMap, request)) {
      result.add(flashMap);
    }
  }
  if (!result.isEmpty()) {
    Collections.sort(result);
    if (logger.isTraceEnabled()) {
      logger.trace("Found " + result.get(0));
    }
    return result.get(0);
  }
  return null;
}

代码示例来源:origin: prestodb/presto

/**
 * possiblePlans should be provided in layout preference order
 */
private PlanWithProperties pickPlan(List<PlanWithProperties> possiblePlans, PreferredProperties preferredProperties)
{
  checkArgument(!possiblePlans.isEmpty());
  if (preferStreamingOperators) {
    possiblePlans = new ArrayList<>(possiblePlans);
    Collections.sort(possiblePlans, Comparator.comparing(PlanWithProperties::getProperties, streamingExecutionPreference(preferredProperties))); // stable sort; is Collections.min() guaranteed to be stable?
  }
  return possiblePlans.get(0);
}

代码示例来源:origin: google/guava

public void testArbitrary_withoutCollisions() {
 List<Object> list = Lists.newArrayList();
 for (int i = 0; i < 50; i++) {
  list.add(new Object());
 }
 Ordering<Object> arbitrary = Ordering.arbitrary();
 Collections.sort(list, arbitrary);
 // Now we don't care what order it's put the list in, only that
 // comparing any pair of elements gives the answer we expect.
 Helpers.testComparator(arbitrary, list);
 assertEquals("Ordering.arbitrary()", arbitrary.toString());
}

代码示例来源:origin: org.mockito/mockito-core

private Constructor<?> biggestConstructor(Class<?> clazz) {
    final List<? extends Constructor<?>> constructors = Arrays.asList(clazz.getDeclaredConstructors());
    Collections.sort(constructors, byParameterNumber);
    Constructor<?> constructor = constructors.get(0);
    checkParameterized(constructor, field);
    return constructor;
  }
}

代码示例来源:origin: MovingBlocks/Terasology

private void sortLibrary() {
  categories = Lists.newArrayList(categoryComponents.keySet());
  Collections.sort(categories);
  for (String category : categories) {
    Collections.sort(categoryComponents.get(category), COMPARE_BY_NAME);
  }
}

代码示例来源:origin: junit-team/junit4

public List<TestRule> getOrderedRules() {
    Collections.sort(entries, RuleContainer.ENTRY_COMPARATOR);
    List<TestRule> result = new ArrayList<TestRule>(entries.size());
    for (RuleContainer.RuleEntry entry : entries) {
      result.add((TestRule) entry.rule);
    }
    return result;
  }
}

代码示例来源:origin: spring-projects/spring-framework

private void startBeans(boolean autoStartupOnly) {
  Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
  Map<Integer, LifecycleGroup> phases = new HashMap<>();
  lifecycleBeans.forEach((beanName, bean) -> {
    if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
      int phase = getPhase(bean);
      LifecycleGroup group = phases.get(phase);
      if (group == null) {
        group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
        phases.put(phase, group);
      }
      group.add(beanName, bean);
    }
  });
  if (!phases.isEmpty()) {
    List<Integer> keys = new ArrayList<>(phases.keySet());
    Collections.sort(keys);
    for (Integer key : keys) {
      phases.get(key).start();
    }
  }
}

代码示例来源:origin: spring-projects/spring-framework

private static String[] calculateMatches(final String name, Class<?> clazz, final int maxDistance) {
  final List<String> candidates = new ArrayList<>();
  ReflectionUtils.doWithFields(clazz, field -> {
    String possibleAlternative = field.getName();
    if (calculateStringDistance(name, possibleAlternative) <= maxDistance) {
      candidates.add(possibleAlternative);
    }
  });
  Collections.sort(candidates);
  return StringUtils.toStringArray(candidates);
}

相关文章

微信公众号

最新文章

更多

Collections类方法