Tabnine Logo
Collections.sort
Code IndexAdd Tabnine to your IDE (free)

How to use
sort
method
in
java.util.Collections

Best Java code snippets using java.util.Collections.sort (Showing top 20 results out of 84,753)

Refine searchRefine arrow

  • List.add
  • List.size
  • List.get
  • ArrayList.<init>
  • Map.get
  • PrintStream.println
  • Map.put
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);
}
java.utilCollectionssort

Javadoc

Sorts the given list in ascending natural order. The algorithm is stable which means equal elements don't get reordered.

Popular methods of Collections

  • emptyList
    Returns the empty list (immutable). This list is serializable.This example illustrates the type-safe
  • singletonList
    Returns an immutable list containing only the specified object. The returned list is serializable.
  • unmodifiableList
    Returns an unmodifiable view of the specified list. This method allows modules to provide users with
  • emptyMap
    Returns the empty map (immutable). This map is serializable.This example illustrates the type-safe w
  • emptySet
    Returns the empty set (immutable). This set is serializable. Unlike the like-named field, this metho
  • unmodifiableMap
    Returns an unmodifiable view of the specified map. This method allows modules to provide users with
  • singleton
    Returns an immutable set containing only the specified object. The returned set is serializable.
  • unmodifiableSet
    Returns an unmodifiable view of the specified set. This method allows modules to provide users with
  • singletonMap
    Returns an immutable map, mapping only the specified key to the specified value. The returned map is
  • addAll
    Adds all of the specified elements to the specified collection. Elements to be added may be specifie
  • reverse
    Reverses the order of the elements in the specified list. This method runs in linear time.
  • unmodifiableCollection
    Returns an unmodifiable view of the specified collection. This method allows modules to provide user
  • reverse,
  • unmodifiableCollection,
  • shuffle,
  • enumeration,
  • list,
  • synchronizedMap,
  • synchronizedList,
  • reverseOrder,
  • emptyIterator

Popular in Java

  • Making http requests using okhttp
  • scheduleAtFixedRate (ScheduledExecutorService)
  • onCreateOptionsMenu (Activity)
  • getExternalFilesDir (Context)
  • EOFException (java.io)
    Thrown when a program encounters the end of a file or stream during an input operation.
  • FileOutputStream (java.io)
    An output stream that writes bytes to a file. If the output file exists, it can be replaced or appen
  • Runnable (java.lang)
    Represents a command that can be executed. Often used to run code in a different Thread.
  • UnknownHostException (java.net)
    Thrown when a hostname can not be resolved.
  • BitSet (java.util)
    The BitSet class implements abit array [http://en.wikipedia.org/wiki/Bit_array]. Each element is eit
  • CountDownLatch (java.util.concurrent)
    A synchronization aid that allows one or more threads to wait until a set of operations being perfor
  • Top plugins for Android Studio
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now