Java Code Examples for java.util.Comparator

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project cascading, under directory /src/core/cascading/flow/stream/.

Source file: SparseTupleComparator.java

  19 
vote

@Override public int compare(Tuple lhs,Tuple rhs){
  for (int i=0; i < comparators.length; i++) {
    Comparator comparator=comparators[i];
    if (comparator == null)     continue;
    Integer pos=posMap[i];
    int c=comparator.compare(lhs.getObject(pos),rhs.getObject(pos));
    if (c != 0)     return c;
  }
  return 0;
}
 

Example 2

From project BDSup2Sub, under directory /src/main/java/bdsup2sub/cli/.

Source file: CommandLineParser.java

  16 
vote

public void printHelp(){
  HelpFormatter formatter=new HelpFormatter();
  formatter.setOptionComparator(new Comparator(){
    @Override public int compare(    Object o1,    Object o2){
      Option opt1=(Option)o1;
      Option opt2=(Option)o2;
      int opt1Index=OPTION_ORDER.indexOf(opt1.getOpt());
      int opt2Index=OPTION_ORDER.indexOf(opt2.getOpt());
      return (int)Math.signum(opt1Index - opt2Index);
    }
  }
);
  formatter.setWidth(79);
  formatter.printHelp("java -jar BDSup2Sub [options] -o <output> <input>",options);
}
 

Example 3

From project activiti-webapp-rest-generic, under directory /activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/dto/.

Source file: TreeFolderDto.java

  15 
vote

public void sortChildNodes(){
  Collections.sort(children,new Comparator<TreeNodeDto>(){
    public int compare(    TreeNodeDto arg0,    TreeNodeDto arg1){
      if (arg0 instanceof TreeFolderDto) {
        if (arg1 instanceof TreeFolderDto) {
          return arg0.getLabel().compareTo(arg1.getLabel());
        }
        return -1;
      }
      if (arg1 instanceof TreeFolderDto) {
        return 1;
      }
      return arg0.getLabel().compareTo(arg1.getLabel());
    }
  }
);
}
 

Example 4

From project agorava-twitter, under directory /agorava-twitter-cdi/src/main/java/org/agorava/twitter/jackson/.

Source file: AbstractTrendsList.java

  15 
vote

public AbstractTrendsList(Map<String,List<Trend>> trends,DateFormat dateFormat){
  list=new ArrayList<Trends>(trends.size());
  for (Iterator<Entry<String,List<Trend>>> trendsIt=trends.entrySet().iterator(); trendsIt.hasNext(); ) {
    Entry<String,List<Trend>> entry=trendsIt.next();
    list.add(new Trends(toDate(entry.getKey(),dateFormat),entry.getValue()));
  }
  Collections.sort(list,new Comparator<Trends>(){
    public int compare(    Trends t1,    Trends t2){
      return t1.getTime().getTime() > t2.getTime().getTime() ? -1 : 1;
    }
  }
);
}
 

Example 5

From project Agot-Java, under directory /src/main/java/got/pojo/.

Source file: GameInfo.java

  15 
vote

public List<FamilyInfo> orderByCompetePower(){
  List<FamilyInfo> competeFamilies=new ArrayList<FamilyInfo>();
  for (  FamilyInfo fi : addrmap.values()) {
    competeFamilies.add(fi);
  }
  Collections.sort(competeFamilies,new Comparator<FamilyInfo>(){
    @Override public int compare(    FamilyInfo o1,    FamilyInfo o2){
      return (o1.getCompetePower() > o2.getCompetePower() ? -1 : (o1.getCompetePower() == o2.getCompetePower() ? 0 : 1));
    }
  }
);
  return competeFamilies;
}
 

Example 6

From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/helper/.

Source file: SelectSensorHelper.java

  15 
vote

private List<Sensor> sortedSensors(){
  final List<Sensor> sensors=sensorManager.getSensors();
  sort(sensors,new Comparator<Sensor>(){
    @Override public int compare(    Sensor sensor,    Sensor sensor1){
      return sensor.toString().compareTo(sensor1.toString());
    }
  }
);
  return sensors;
}
 

Example 7

From project ajah, under directory /ajah-util/src/main/java/com/ajah/util/compare/.

Source file: CompositeComparator.java

  15 
vote

/** 
 * Creates an instance with child comparators.
 * @param comparators
 */
@SafeVarargs public CompositeComparator(final Comparator<T>... comparators){
  if (comparators == null || comparators.length == 0) {
    throw new IllegalArgumentException("Must include at least one child comparator");
  }
  this.comparators=comparators;
}
 

Example 8

From project AlgorithmsNYC, under directory /Algorithms/Heap/.

Source file: GevorgHeap.java

  15 
vote

/** 
 * Constructor
 */
public GevorgHeap(Comparator<Integer> heapProperty){
  this.Heap_Property=heapProperty;
  data=new int[16];
  mapping=new HashMap<Integer,Integer>();
  size=0;
  System.out.println("New Heap:\n" + this);
}
 

Example 9

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/sqljep/function/.

Source file: ComparativeAND.java

  15 
vote

@SuppressWarnings("unchecked") public boolean intersect(int function,Comparable other,Comparator comparator){
  for (  Comparative source : list) {
    if (!source.intersect(function,other,comparator)) {
      return false;
    }
  }
  return true;
}
 

Example 10

From project amplafi-sworddance, under directory /src/main/java/com/sworddance/taskcontrol/.

Source file: ResourceLockManager.java

  15 
vote

public synchronized void addTaskLocks(PrioritizedTask task,Comparator<ResourceLock> insertionComparator){
synchronized (tasksAdded) {
    if (tasksAdded.contains(task)) {
      throw new RuntimeException(task.getName() + ":task already has added locks");
    }
    tasksAdded.add(task);
  }
  ResourceLock globalLock=null;
  ArrayList<ResourceLock> taskLocks=new ArrayList<ResourceLock>(task.getResourceLocksNeeded());
  for (  ResourceLock lock : taskLocks) {
    lock.setTask(task);
  }
  for (  ResourceLock lock : taskLocks) {
    if (GLOBALRESOURCE.equals(lock.getResourceName())) {
      globalLock=lock;
      if (globalLock.isExclusiveLock() && !globalLock.isLockReleased()) {
        for (        Map.Entry<?,?> entry : lockLists.entrySet()) {
          String resourceName=entry.getKey().toString();
          if (!GLOBALRESOURCE.equals(resourceName)) {
            ResourceLock newLock=new ResourceLock(resourceName,globalLock.getLockType());
            addGeneratedLock(task,newLock,insertionComparator);
          }
        }
      }
    }
    addLock(lock,insertionComparator);
  }
  if (globalLock == null) {
    globalLock=createGlobalResourceNonexclusiveLock();
    addGeneratedLock(task,globalLock,insertionComparator);
  }
}
 

Example 11

From project and-bible, under directory /AndBible/src/net/bible/android/view/activity/base/.

Source file: DocumentSelectionBase.java

  15 
vote

/** 
 * a spinner has changed so refilter the doc list
 */
private void filterDocuments(){
  try {
    if (allDocuments != null && allDocuments.size() > 0) {
      Log.d(TAG,"filtering documents");
      displayedDocuments.clear();
      Language lang=languageList.get(selectedLanguageNo);
      for (      Book doc : allDocuments) {
        BookFilter filter=DOCUMENT_TYPE_SPINNER_FILTERS[selectedDocumentFilterNo];
        if (filter.test(doc) && doc.getLanguage().equals(lang)) {
          displayedDocuments.add(doc);
        }
      }
      Collections.sort(displayedDocuments,new Comparator<Book>(){
        public int compare(        Book o1,        Book o2){
          return o1.getInitials().compareToIgnoreCase(o2.getInitials());
        }
      }
);
      notifyDataSetChanged();
    }
  }
 catch (  Exception e) {
    Log.e(TAG,"Error initialising view",e);
    Toast.makeText(this,getString(R.string.error) + e.getMessage(),Toast.LENGTH_SHORT);
  }
}
 

Example 12

From project Android, under directory /app/src/main/java/com/github/mobile/persistence/.

Source file: OrganizationRepositories.java

  15 
vote

@Override public List<Repository> request() throws IOException {
  if (isAuthenticatedUser()) {
    Set<Repository> all=new TreeSet<Repository>(new Comparator<Repository>(){
      public int compare(      final Repository repo1,      final Repository repo2){
        final long id1=repo1.getId();
        final long id2=repo2.getId();
        if (id1 > id2)         return 1;
        if (id1 < id2)         return -1;
        return 0;
      }
    }
);
    all.addAll(repos.getRepositories());
    all.addAll(watcher.getWatched());
    return new ArrayList<Repository>(all);
  }
 else   return repos.getOrgRepositories(org.getLogin());
}
 

Example 13

From project android-api-demos, under directory /src/com/mobeelizer/demos/adapters/.

Source file: RelationsSyncAdapter.java

  15 
vote

/** 
 * Gives the ability to sort the  {@link ExpandableListView}. At first the group are sorted, then groups items. In the default implementation sorting take into account only the name or title filed.
 * @param groupComparator Comparator used to sort group entities
 * @param itemComparator Comparator used to sort item entities
 */
public void sort(final Comparator<GraphsConflictsOrderEntity> groupComparator,final Comparator<GraphsConflictsItemEntity> itemComparator){
  Collections.sort(mOrders,groupComparator);
  for (  GraphsConflictsOrderEntity gOrder : mOrders) {
    Collections.sort(mItems.get(gOrder.getGuid()),itemComparator);
  }
}
 

Example 14

From project android-client_2, under directory /src/org/mifos/androidclient/entities/simple/.

Source file: CustomersData.java

  15 
vote

public void sort(){
  if (centers != null) {
    Collections.sort(centers,new Comparator<Center>(){
      @Override public int compare(      Center center1,      Center center2){
        return center1.getDisplayName().compareToIgnoreCase(center2.getDisplayName());
      }
    }
);
  }
}
 

Example 15

From project Android-DB-Editor, under directory /src/com/troido/dbeditor/.

Source file: Device.java

  15 
vote

private void createPackages(List<Database> databases){
  Hashtable<String,Package> packageMap=new Hashtable<String,Package>();
  for (  Database db : databases) {
    Package p=packageMap.get(db.getPackageName());
    if (p == null) {
      p=new Package(db.getPackageName());
      packageMap.put(db.getPackageName(),p);
    }
    p.addDatabase(db);
  }
  packages=packageMap.values().toArray(new Package[0]);
  Arrays.sort(packages,new Comparator<Package>(){
    @Override public int compare(    Package o1,    Package o2){
      return o1.compareTo(o2);
    }
  }
);
}
 

Example 16

From project android-joedayz, under directory /Proyectos/GreenDroid/src/greendroid/widget/.

Source file: ItemAdapter.java

  15 
vote

/** 
 * Sorts the content of this adapter using the specified comparator.
 * @param comparator The comparator used to sort the objects contained inthis adapter.
 */
public void sort(Comparator<? super Item> comparator){
  Collections.sort(mItems,comparator);
  if (mNotifyOnChange) {
    notifyDataSetChanged();
  }
}
 

Example 17

From project Android-MapForgeFragment, under directory /library-common/src/com/jakewharton/android/mapsforge_fragment/.

Source file: CoastlineAlgorithm.java

  15 
vote

/** 
 * Constructs a new CoastlineAlgorithm instance to generate closed polygons.
 */
CoastlineAlgorithm(){
  this.coastlineWayComparator=new Comparator<CoastlineWay>(){
    @Override public int compare(    CoastlineWay o1,    CoastlineWay o2){
      if (o1.entryAngle > o2.entryAngle) {
        return 1;
      }
      return -1;
    }
  }
;
  this.helperPoints=new HelperPoint[4];
  this.helperPoints[0]=new HelperPoint();
  this.helperPoints[1]=new HelperPoint();
  this.helperPoints[2]=new HelperPoint();
  this.helperPoints[3]=new HelperPoint();
  this.additionalCoastlinePoints=new ArrayList<HelperPoint>(4);
  this.coastlineWays=new ArrayList<CoastlineWay>(4);
  this.coastlineSegments=new ArrayList<float[]>(8);
  this.coastlineEnds=new TreeMap<ImmutablePoint,float[]>();
  this.coastlineStarts=new TreeMap<ImmutablePoint,float[]>();
  this.handledCoastlineSegments=new HashSet<EndPoints>(64);
  this.virtualTileBoundaries=new int[4];
}
 

Example 18

From project android-vpn-settings, under directory /src/com/android/settings/vpn/.

Source file: VpnSettings.java

  15 
vote

private void retrieveVpnListFromStorage(){
  mVpnPreferenceMap=new LinkedHashMap<String,VpnPreference>();
  mVpnProfileList=Collections.synchronizedList(new ArrayList<VpnProfile>());
  mVpnListContainer.removeAll();
  File root=new File(PROFILES_ROOT);
  String[] dirs=root.list();
  if (dirs == null)   return;
  for (  String dir : dirs) {
    File f=new File(new File(root,dir),PROFILE_OBJ_FILE);
    if (!f.exists())     continue;
    try {
      VpnProfile p=deserialize(f);
      if (p == null)       continue;
      if (!checkIdConsistency(dir,p))       continue;
      mVpnProfileList.add(p);
    }
 catch (    IOException e) {
      Log.e(TAG,"retrieveVpnListFromStorage()",e);
    }
  }
  Collections.sort(mVpnProfileList,new Comparator<VpnProfile>(){
    public int compare(    VpnProfile p1,    VpnProfile p2){
      return p1.getName().compareTo(p2.getName());
    }
    public boolean equals(    VpnProfile p){
      return false;
    }
  }
);
  for (  VpnProfile p : mVpnProfileList) {
    Preference pref=addPreferenceFor(p,false);
  }
  disableProfilePreferencesIfOneActive();
}
 

Example 19

From project android_5, under directory /src/aarddict/android/.

Source file: SectionMatcher.java

  15 
vote

public boolean match(String section,String candidate,int strength){
  Comparator<Entry> c=EntryComparators.ALL[strength];
  Entry e1=new Entry(null,section.trim());
  Entry e2=new Entry(null,candidate.trim());
  boolean result=c.compare(e1,e2) == 0;
  Log.d(TAG,String.format("Match section <%s> candidate <%s> strength <%s> match? %s",section,candidate,strength,result));
  return result;
}
 

Example 20

From project android_aosp_packages_apps_Settings, under directory /src/com/android/settings/applications/.

Source file: ApplicationsState.java

  15 
vote

ArrayList<AppEntry> rebuild(AppFilter filter,Comparator<AppEntry> comparator){
synchronized (mRebuildSync) {
    mRebuildRequested=true;
    mRebuildAsync=false;
    mRebuildFilter=filter;
    mRebuildComparator=comparator;
    mRebuildResult=null;
    if (!mBackgroundHandler.hasMessages(BackgroundHandler.MSG_REBUILD_LIST)) {
      mBackgroundHandler.sendEmptyMessage(BackgroundHandler.MSG_REBUILD_LIST);
    }
    long waitend=SystemClock.uptimeMillis() + 250;
    while (mRebuildResult == null) {
      long now=SystemClock.uptimeMillis();
      if (now >= waitend) {
        break;
      }
      try {
        mRebuildSync.wait(waitend - now);
      }
 catch (      InterruptedException e) {
      }
    }
    mRebuildAsync=true;
    return mRebuildResult;
  }
}
 

Example 21

From project android_external_guava, under directory /src/com/google/common/collect/.

Source file: CompoundOrdering.java

  15 
vote

public int compare(T left,T right){
  for (  Comparator<? super T> comparator : comparators) {
    int result=comparator.compare(left,right);
    if (result != 0) {
      return result;
    }
  }
  return 0;
}
 

Example 22

From project android_external_libphonenumber, under directory /java/src/com/android/i18n/phonenumbers/geocoding/.

Source file: FlyweightMapStorage.java

  15 
vote

@Override public void readFromSortedMap(SortedMap<Integer,String> sortedAreaCodeMap){
  SortedSet<String> descriptionsSet=new TreeSet<String>();
  numOfEntries=sortedAreaCodeMap.size();
  prefixSizeInBytes=getOptimalNumberOfBytesForValue(sortedAreaCodeMap.lastKey());
  phoneNumberPrefixes=ByteBuffer.allocate(numOfEntries * prefixSizeInBytes);
  int index=0;
  for (  Entry<Integer,String> entry : sortedAreaCodeMap.entrySet()) {
    int prefix=entry.getKey();
    storeWordInBuffer(phoneNumberPrefixes,prefixSizeInBytes,index++,prefix);
    possibleLengths.add((int)Math.log10(prefix) + 1);
    descriptionsSet.add(entry.getValue());
  }
  descIndexSizeInBytes=getOptimalNumberOfBytesForValue(descriptionsSet.size() - 1);
  descriptionIndexes=ByteBuffer.allocate(numOfEntries * descIndexSizeInBytes);
  descriptionPool=new String[descriptionsSet.size()];
  descriptionsSet.toArray(descriptionPool);
  index=0;
  for (int i=0; i < numOfEntries; i++) {
    int prefix=readWordFromBuffer(phoneNumberPrefixes,prefixSizeInBytes,i);
    String description=sortedAreaCodeMap.get(prefix);
    int positionInDescriptionPool=Arrays.binarySearch(descriptionPool,description,new Comparator<String>(){
      public int compare(      String o1,      String o2){
        return o1.compareTo(o2);
      }
    }
);
    storeWordInBuffer(descriptionIndexes,descIndexSizeInBytes,index++,positionInDescriptionPool);
  }
}
 

Example 23

From project android_packages_apps_FileManager, under directory /src/org/openintents/filemanager/.

Source file: DirectoryScanner.java

  15 
vote

public static Comparator<File> getForFile(int comparator,boolean ascending){
switch (comparator) {
case NAME:
    return new NameComparator(ascending);
case SIZE:
  return new SizeComparator(ascending);
case LAST_MODIFIED:
return new LastModifiedComparator(ascending);
default :
return null;
}
}
 

Example 24

From project android_packages_apps_Gallery2, under directory /src/com/android/gallery3d/data/.

Source file: LocalAlbumSet.java

  15 
vote

private MediaSet getLocalAlbum(DataManager manager,int type,Path parent,int id,String name){
synchronized (DataManager.LOCK) {
    Path path=parent.getChild(id);
    MediaObject object=manager.peekMediaObject(path);
    if (object != null)     return (MediaSet)object;
switch (type) {
case MEDIA_TYPE_IMAGE:
      return new LocalAlbum(path,mApplication,id,true,name);
case MEDIA_TYPE_VIDEO:
    return new LocalAlbum(path,mApplication,id,false,name);
case MEDIA_TYPE_ALL:
  Comparator<MediaItem> comp=DataManager.sDateTakenComparator;
return new LocalMergeAlbum(path,comp,new MediaSet[]{getLocalAlbum(manager,MEDIA_TYPE_IMAGE,PATH_IMAGE,id,name),getLocalAlbum(manager,MEDIA_TYPE_VIDEO,PATH_VIDEO,id,name)},id);
}
throw new IllegalArgumentException(String.valueOf(type));
}
}
 

Example 25

From project android_packages_apps_phone, under directory /src/com/android/phone/sip/.

Source file: SipSettings.java

  15 
vote

private void retrieveSipLists(){
  mSipPreferenceMap=new LinkedHashMap<String,SipPreference>();
  mSipProfileList=mProfileDb.retrieveSipProfileList();
  processActiveProfilesFromSipService();
  Collections.sort(mSipProfileList,new Comparator<SipProfile>(){
    public int compare(    SipProfile p1,    SipProfile p2){
      return getProfileName(p1).compareTo(getProfileName(p2));
    }
    public boolean equals(    SipProfile p){
      return false;
    }
  }
);
  mSipListContainer.removeAll();
  for (  SipProfile p : mSipProfileList) {
    addPreferenceFor(p);
  }
  if (!mSipSharedPreferences.isReceivingCallsEnabled())   return;
  for (  SipProfile p : mSipProfileList) {
    if (mUid == p.getCallingUid()) {
      try {
        mSipManager.setRegistrationListener(p.getUriString(),createRegistrationListener());
      }
 catch (      SipException e) {
        Log.e(TAG,"cannot set registration listener",e);
      }
    }
  }
}
 

Example 26

From project android_packages_apps_QuickSearchBox, under directory /tests/src/com/android/quicksearchbox/.

Source file: LexicographicalCorpusRanker.java

  15 
vote

@Override public List<Corpus> rankCorpora(Corpora corpora){
  ArrayList<Corpus> ordered=new ArrayList<Corpus>(corpora.getEnabledCorpora());
  Collections.sort(ordered,new Comparator<Corpus>(){
    public int compare(    Corpus c1,    Corpus c2){
      return c1.getName().compareTo(c2.getName());
    }
  }
);
  return ordered;
}
 

Example 27

From project android_wallpaper_flier, under directory /src/fi/harism/wallpaper/flier/.

Source file: FlierClouds.java

  15 
vote

/** 
 * Sorts clouds based on their z value.
 */
public void sortClouds(){
  final Comparator<StructCloud> comparator=new Comparator<StructCloud>(){
    @Override public int compare(    StructCloud arg0,    StructCloud arg1){
      float z0=arg0.mZValue;
      float z1=arg1.mZValue;
      return z0 == z1 ? 0 : z0 < z1 ? 1 : -1;
    }
  }
;
  Arrays.sort(mClouds,comparator);
}
 

Example 28

From project ANNIS, under directory /annis-gui/src/main/java/annis/gui/visualizers/component/grid/.

Source file: GridVisualizer.java

  15 
vote

/** 
 * Sort events of a row. The sorting is depending on the left value of the event
 * @param row 
 */
private void sortEventsByTokenIndex(Row row){
  Collections.sort(row.getEvents(),new Comparator<GridEvent>(){
    @Override public int compare(    GridEvent o1,    GridEvent o2){
      if (o1 == o2) {
        return 0;
      }
      if (o1 == null) {
        return -1;
      }
      if (o2 == null) {
        return +1;
      }
      return ((Integer)o1.getLeft()).compareTo(o2.getLeft());
    }
  }
);
}
 

Example 29

From project ant4eclipse, under directory /org.ant4eclipse.lib.core/src/org/ant4eclipse/lib/core/util/.

Source file: StopWatchServiceImpl.java

  15 
vote

public void dumpAll(){
  dumpAll("total time:",new Comparator<StopWatch>(){
    public int compare(    StopWatch o1,    StopWatch o2){
      return Long.valueOf(o2.getElapsedTime()).compareTo(o1.getElapsedTime());
    }
  }
);
}
 

Example 30

From project AnySoftKeyboard, under directory /src/com/anysoftkeyboard/addons/.

Source file: AddOnsFactory.java

  15 
vote

protected void loadAddOns(final Context askContext){
  clearAddOnList();
  mAddOns.addAll(getAddOnsFromResId(askContext,mBuildInAddOnsResId));
  mAddOns.addAll(getExternalAddOns(askContext));
  buildOtherDataBasedOnNewAddOns(mAddOns);
  Collections.sort(mAddOns,new Comparator<AddOn>(){
    public int compare(    AddOn k1,    AddOn k2){
      Context c1=k1.getPackageContext();
      Context c2=k2.getPackageContext();
      if (c1 == null)       c1=askContext;
      if (c2 == null)       c2=askContext;
      if (c1 == c2)       return k1.getSortIndex() - k2.getSortIndex();
 else       if (c1 == askContext)       return -1;
 else       if (c2 == askContext)       return 1;
 else       return c1.getPackageName().compareToIgnoreCase(c2.getPackageName());
    }
  }
);
}
 

Example 31

From project apb, under directory /modules/apb-base/src/apb/idegen/.

Source file: IdegenTask.java

  15 
vote

/** 
 * Constructs a Project
 * @param id                 The module Id
 * @param modulesHome        a path to the modules files
 * @param projectDirectory   a path to a project directory
 */
protected Project(@NotNull String id,@NotNull File modulesHome,File projectDirectory){
  super(id,modulesHome);
  jdkName="";
  this.projectDirectory=projectDirectory;
  modules=new TreeSet<String>();
  libraries=new TreeSet<Library>(new Comparator<Library>(){
    @Override public int compare(    Library o1,    Library o2){
      final int c=o1.getClass().getName().compareTo(o2.getClass().getName());
      return c != 0 ? c : o1.getName().compareTo(o2.getName());
    }
  }
);
}
 

Example 32

From project Apertiurm-Androind-app-devlopment, under directory /ApertiumAndroid/src/org/apertium/android/.

Source file: SMSInboxActivity.java

  15 
vote

private void fill(){
  this.setTitle(getString(R.string.inbox));
  List<SMSobject> dir=getSms();
  Comparator<Object> comparator=Collections.reverseOrder();
  Collections.sort(dir,comparator);
  adapter=new SmsArrayAdapter(SMSInboxActivity.this,R.layout.sms_layout,dir);
  this.setListAdapter(adapter);
}
 

Example 33

From project appengine-java-mapreduce, under directory /java/src/com/google/appengine/tools/mapreduce/inputs/.

Source file: DatastoreInput.java

  15 
vote

private Collection<Key> chooseSplitPoints(DatastoreService datastoreService){
  int desiredScatterResultCount=shardCount * SCATTER_OVERSAMPLE_FACTOR;
  Query scatter=new Query(entityKind).addSort(SCATTER_RESERVED_PROPERTY).setKeysOnly();
  List<Entity> scatterList=datastoreService.prepare(scatter).asList(withLimit(desiredScatterResultCount));
  Collections.sort(scatterList,new Comparator<Entity>(){
    @Override public int compare(    Entity o1,    Entity o2){
      return o1.getKey().compareTo(o2.getKey());
    }
  }
);
  Collection<Key> splitKeys=new ArrayList<Key>(shardCount);
  int usedOversampleFactor=Math.max(1,scatterList.size() / shardCount);
  logger.info("Requested " + desiredScatterResultCount + " scatter entities. Got "+ scatterList.size()+ " so using oversample factor "+ usedOversampleFactor);
  for (int i=1; i < shardCount; i++) {
    if (i * usedOversampleFactor >= scatterList.size()) {
      break;
    }
    splitKeys.add(scatterList.get(i * usedOversampleFactor).getKey());
  }
  return splitKeys;
}
 

Example 34

From project apps-for-android, under directory /AndroidGlobalTime/src/com/android/globaltime/.

Source file: City.java

  15 
vote

/** 
 * Returns the cities, ordered by offset, accounting for summer/daylight savings time.  This requires reading the entire time zone database behind the scenes.
 */
public static City[] getCitiesByOffset(){
  City[] ocities=cities.values().toArray(new City[0]);
  Arrays.sort(ocities,new Comparator<City>(){
    public int compare(    City c1,    City c2){
      long now=System.currentTimeMillis();
      TimeZone tz1=c1.getTimeZone();
      TimeZone tz2=c2.getTimeZone();
      int off1=tz1.getOffset(now);
      int off2=tz2.getOffset(now);
      if (off1 == off2) {
        float dlat=c2.getLatitude() - c1.getLatitude();
        if (dlat < 0.0f)         return -1;
        if (dlat > 0.0f)         return 1;
        return 0;
      }
      return off1 - off2;
    }
  }
);
  return ocities;
}
 

Example 35

From project archive-commons, under directory /ia-tools/src/main/java/org/archive/hadoop/cdx/.

Source file: CDXClusterRangeDumper.java

  15 
vote

public int run(String[] args) throws Exception {
  if (args.length < 3) {
    return USAGE(1);
  }
  String start=args[0];
  String end=args[1];
  Iterator<String> itr;
  if (args.length == 3) {
    Path clusterPath=new Path(args[2]);
    CDXCluster c=new CDXCluster(getConf(),clusterPath);
    itr=c.getRange(start,end);
  }
 else {
    Comparator<String> comparator=new Comparator<String>(){
      public int compare(      String s1,      String s2){
        return s1.compareTo(s2);
      }
    }
;
    SortedCompositeIterator<String> scitr=new SortedCompositeIterator<String>(comparator);
    for (int i=2; i < args.length; i++) {
      Path clusterPath=new Path(args[i]);
      CDXCluster c=new CDXCluster(getConf(),clusterPath);
      scitr.addIterator(c.getRange(start,end));
    }
    itr=scitr;
  }
  PrintWriter pw=new PrintWriter(new OutputStreamWriter(System.out,UTF8));
  while (itr.hasNext()) {
    pw.println(itr.next());
  }
  pw.flush();
  pw.close();
  return 0;
}
 

Example 36

From project ardverk-commons, under directory /src/main/java/org/ardverk/utils/.

Source file: ArrayUtils.java

  15 
vote

/** 
 * Returns the min and max value in the given array.
 */
public static <T>T[] mm(Comparator<T> comparator,T[] values,int offset,int length){
  checkBounds(values,offset,length);
  T min=values[offset];
  T max=min;
  int end=offset + length;
  while (++offset < end) {
    T value=values[offset];
    if (comparator.compare(value,min) < 0) {
      min=value;
    }
 else     if (0 < comparator.compare(value,max)) {
      max=value;
    }
  }
  Class<?> clazz=values.getClass();
  Class<?> componentType=clazz.getComponentType();
  @SuppressWarnings("unchecked") T[] dst=(T[])Array.newInstance(componentType,2);
  dst[0]=min;
  dst[1]=max;
  return dst;
}
 

Example 37

From project ardverk-dht, under directory /components/core/src/test/java/org/ardverk/dht/io/.

Source file: LookupResponseHandlerTest.java

  15 
vote

@Test public void pollFirst(){
  KUID lookupId=KUID.createRandom(20);
  Comparator<Identifier> comparator=new XorComparator(lookupId);
  List<KUID> contacts1=new ArrayList<KUID>();
  TreeSet<KUID> contacts2=new TreeSet<KUID>(comparator);
  for (int i=0; i < 100; i++) {
    KUID contact=KUID.createRandom(lookupId);
    contacts1.add(contact);
    contacts2.add(contact);
  }
  Collections.sort(contacts1,comparator);
  KUID[] contacts3=contacts2.toArray(new KUID[0]);
  TestCase.assertEquals(contacts1.size(),contacts2.size());
  TestCase.assertEquals(contacts1.size(),contacts3.length);
  for (int i=0; i < contacts1.size(); i++) {
    KUID contact1=contacts1.get(i);
    KUID contact2=contacts2.pollFirst();
    KUID contact3=contacts3[i];
    TestCase.assertEquals(contact1,contact2);
    TestCase.assertEquals(contact1,contact3);
    TestCase.assertEquals(contact2,contact3);
  }
}
 

Example 38

From project Arecibo, under directory /dashboard/src/main/java/com/ning/arecibo/dashboard/format/.

Source file: DashboardFormatManager.java

  15 
vote

@Override public Comparator<String> getSubTitleOrderingComparator(){
  return new Comparator<String>(){
    public int compare(    String s1,    String s2){
      Integer i1=subTitleOrderMap.get(s1);
      Integer i2=subTitleOrderMap.get(s2);
      int compare=integerCompare(i1,i2);
      if (compare == 0)       compare=s1.compareTo(s2);
      return compare;
    }
  }
;
}
 

Example 39

From project arquillian-core, under directory /container/spi/src/main/java/org/jboss/arquillian/container/spi/client/deployment/.

Source file: DeploymentScenario.java

  15 
vote

public List<Deployment> managedDeploymentsInDeployOrder(){
  List<Deployment> managedDeployment=new ArrayList<Deployment>();
  for (  Deployment deployment : deployments) {
    DeploymentDescription desc=deployment.getDescription();
    if (desc.managed()) {
      managedDeployment.add(deployment);
    }
  }
  Collections.sort(managedDeployment,new Comparator<Deployment>(){
    public int compare(    Deployment o1,    Deployment o2){
      return new Integer(o1.getDescription().getOrder()).compareTo(o2.getDescription().getOrder());
    }
  }
);
  return Collections.unmodifiableList(managedDeployment);
}
 

Example 40

From project arquillian_deprecated, under directory /spi/src/main/java/org/jboss/arquillian/spi/client/deployment/.

Source file: DeploymentScenario.java

  15 
vote

/** 
 * Get all  {@link DeploymentDescription} defined to be deployed during Test startup for a specific {@link TargetDescription} ordered.
 * @param target The Target to filter on
 * @return A List of found {@link DeploymentDescription}. Will return a empty list if none are found.
 */
public List<DeploymentDescription> getStartupDeploymentsFor(TargetDescription target){
  Validate.notNull(target,"Target must be specified");
  List<DeploymentDescription> startupDeployments=new ArrayList<DeploymentDescription>();
  for (  DeploymentDescription deployment : deployments) {
    if (deployment.managed() && target.equals(deployment.getTarget())) {
      startupDeployments.add(deployment);
    }
  }
  Collections.sort(startupDeployments,new Comparator<DeploymentDescription>(){
    public int compare(    DeploymentDescription o1,    DeploymentDescription o2){
      return new Integer(o1.getOrder()).compareTo(o2.getOrder());
    }
  }
);
  return Collections.unmodifiableList(startupDeployments);
}
 

Example 41

From project artifactory-plugin, under directory /src/main/java/org/jfrog/hudson/.

Source file: ArtifactoryServer.java

  15 
vote

private void gatherUserPluginInfo(List<UserPluginInfo> infosToReturn,String pluginKey){
  Credentials resolvingCredentials=getResolvingCredentials();
  ArtifactoryBuildInfoClient client=createArtifactoryClient(resolvingCredentials.getUsername(),resolvingCredentials.getPassword(),createProxyConfiguration(Jenkins.getInstance().proxy));
  try {
    Map<String,List<Map>> userPluginInfo=client.getUserPluginInfo();
    if (userPluginInfo != null && userPluginInfo.containsKey(pluginKey)) {
      List<Map> stagingUserPluginInfo=userPluginInfo.get(pluginKey);
      if (stagingUserPluginInfo != null) {
        for (        Map stagingPluginInfo : stagingUserPluginInfo) {
          infosToReturn.add(new UserPluginInfo(stagingPluginInfo));
        }
        Collections.sort(infosToReturn,new Comparator<UserPluginInfo>(){
          public int compare(          UserPluginInfo o1,          UserPluginInfo o2){
            return o1.getPluginName().compareTo(o2.getPluginName());
          }
        }
);
      }
    }
  }
 catch (  IOException e) {
    log.log(Level.WARNING,"Failed to obtain user plugin info: " + e.getMessage());
  }
 finally {
    client.shutdown();
  }
}
 

Example 42

From project atlas, under directory /src/test/java/com/ning/atlas/.

Source file: TestJRubyTemplateParser.java

  15 
vote

@Test public void testExternalSystem() throws Exception {
  JRubyTemplateParser p=new JRubyTemplateParser();
  Template t=p.parseSystem(new File("src/test/ruby/ex1/system-template-with-external.rb")).get(0);
  Environment env=p.parseEnvironment(new File("src/test/ruby/ex1/env-with-listener.rb")).get(0);
  SystemMap map=t.normalize(env);
  SortedSet<Host> hosts=Sets.newTreeSet(new Comparator<Host>(){
    @Override public int compare(    Host host,    Host host1){
      return host.getId().toExternalForm().compareTo(host1.getId().toExternalForm());
    }
  }
);
  hosts.addAll(map.findLeaves());
  assertThat(hosts.size(),equalTo(3));
  Iterator<Host> itty=hosts.iterator();
  Host one=itty.next();
  System.out.println(one.getId());
  Host two=itty.next();
  System.out.println(two.getId());
  Host three=itty.next();
  System.out.println(three.getId());
}
 

Example 43

From project atlassian-rest-cli, under directory /rest-cli-runner/src/main/java/com/galeoconsulting/leonardinius/api/impl/.

Source file: ServletVelocityHelperImpl.java

  15 
vote

@Override public List<SessionBean> getAllSessionBeans(){
  List<SessionBean> list=Lists.newArrayList();
  for (  Map.Entry<SessionId,ScriptSession> entry : sessionManager.listAllSessions().entrySet()) {
    list.add(SessionBean.newInstance(entry.getKey(),entry.getValue(),getUserProfile(entry.getValue().getCreator())));
  }
  Collections.sort(list,new Comparator<SessionBean>(){
    @Override public int compare(    SessionBean o1,    SessionBean o2){
      long cmp;
      if (o2.getCreatedAtTimestamp() < 0) {
        cmp=-(o2.getCreatedAtTimestamp() - o1.getCreatedAtTimestamp());
      }
 else {
        cmp=o1.getCreatedAtTimestamp() - o2.getCreatedAtTimestamp();
      }
      return cmp == 0 ? 0 : cmp < 0 ? -1 : 1;
    }
  }
);
  return list;
}
 

Example 44

From project aws-toolkit-for-eclipse, under directory /com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/.

Source file: TagFormatter.java

  15 
vote

/** 
 * Returns a formatted string representing the tags given. They will be sorted by their keys.
 */
public static String formatTags(List<Tag> tags){
  if (tags == null || tags.isEmpty())   return "";
  Collections.sort(tags,new Comparator<Tag>(){
    public int compare(    Tag o1,    Tag o2){
      return o1.getKey().compareTo(o2.getKey());
    }
  }
);
  StringBuilder allTags=new StringBuilder();
  boolean first=true;
  for (  Tag tag : tags) {
    if (first) {
      first=false;
    }
 else {
      allTags.append("; ");
    }
    allTags.append(tag.getKey()).append("=").append(tag.getValue());
  }
  return allTags.toString();
}
 

Example 45

From project azkaban, under directory /azkaban/src/java/azkaban/flow/.

Source file: GroupedFlow.java

  15 
vote

public GroupedFlow(Flow... flows){
  this.flows=flows;
  this.sortedFlows=Arrays.copyOf(this.flows,this.flows.length);
  Arrays.sort(this.sortedFlows,new Comparator<Flow>(){
    @Override public int compare(    Flow o1,    Flow o2){
      return o1.getName().compareTo(o2.getName());
    }
  }
);
}
 

Example 46

From project babel, under directory /src/babel/content/eqclasses/properties/context/.

Source file: Context.java

  15 
vote

public void pruneContext(int numKeep,Comparator<ContextualItem> comparator){
  if ((m_neighborsMap != null) && (numKeep >= 0) && (m_neighborsMap.size() > numKeep)) {
    LinkedList<ContextualItem> valList=new LinkedList<ContextualItem>(m_neighborsMap.values());
    ContextualItem val;
    Collections.sort(valList,comparator);
    m_neighborsMap.clear();
    for (int i=0; i < Math.min(valList.size(),numKeep); i++) {
      val=valList.get(i);
      m_neighborsMap.put(val.m_contEqID,val);
    }
  }
}
 

Example 47

From project backend-update-center2, under directory /src/main/java/org/jvnet/hudson/update_center/.

Source file: Main.java

  15 
vote

private void buildIndex(File dir,String title,Collection<? extends MavenArtifact> versions,String permalink) throws IOException {
  List<MavenArtifact> list=new ArrayList<MavenArtifact>(versions);
  Collections.sort(list,new Comparator<MavenArtifact>(){
    public int compare(    MavenArtifact o1,    MavenArtifact o2){
      return -o1.getVersion().compareTo(o2.getVersion());
    }
  }
);
  IndexHtmlBuilder index=new IndexHtmlBuilder(dir,title);
  index.add(permalink,"permalink to the latest");
  for (  MavenArtifact a : list)   index.add(a);
  index.close();
}
 

Example 48

From project baseunits, under directory /src/test/java/jp/xet/baseunits/intervals/.

Source file: IntervalComparatorLowerUpperTest.java

  15 
vote

@Test @SuppressWarnings("javadoc") public void test02_NPE(){
  Comparator<Interval<Integer>> c=new IntervalComparatorLowerUpper<Integer>(false,true);
  try {
    c.compare(null,Interval.singleElement(10));
    fail();
  }
 catch (  NullPointerException e) {
  }
}
 

Example 49

From project beam-third-party, under directory /mssl-stereomatcher/src/main/java/uk/ac/ucl/mssl/climatephysics/utilities/.

Source file: ArrayArgSort.java

  15 
vote

public Integer[] indices(){
class NaturalOrdering implements Comparator<Double> {
    public int compare(    Double a,    Double b){
      return a.compareTo(b);
    }
  }
  return indices(new NaturalOrdering());
}
 

Example 50

From project beanstalker, under directory /beanstalk-maven-plugin/src/main/java/br/com/ingenieux/mojo/beanstalk/version/.

Source file: RollbackVersionMojo.java

  15 
vote

@Override protected Object executeInternal() throws MojoExecutionException, MojoFailureException {
  DescribeApplicationVersionsRequest describeApplicationVersionsRequest=new DescribeApplicationVersionsRequest().withApplicationName(applicationName);
  DescribeApplicationVersionsResult appVersions=getService().describeApplicationVersions(describeApplicationVersionsRequest);
  DescribeEnvironmentsRequest describeEnvironmentsRequest=new DescribeEnvironmentsRequest().withApplicationName(applicationName).withEnvironmentIds(environmentId).withEnvironmentNames(environmentName).withIncludeDeleted(false);
  DescribeEnvironmentsResult environments=getService().describeEnvironments(describeEnvironmentsRequest);
  List<ApplicationVersionDescription> appVersionList=new ArrayList<ApplicationVersionDescription>(appVersions.getApplicationVersions());
  List<EnvironmentDescription> environmentList=environments.getEnvironments();
  if (environmentList.isEmpty())   throw new MojoFailureException("No environments were found");
  EnvironmentDescription d=environmentList.get(0);
  Collections.sort(appVersionList,new Comparator<ApplicationVersionDescription>(){
    @Override public int compare(    ApplicationVersionDescription o1,    ApplicationVersionDescription o2){
      return new CompareToBuilder().append(o1.getDateUpdated(),o2.getDateUpdated()).toComparison();
    }
  }
);
  Collections.reverse(appVersionList);
  if (latestVersionInstead) {
    ApplicationVersionDescription latestVersionDescription=appVersionList.get(0);
    return changeToVersion(d,latestVersionDescription);
  }
  ListIterator<ApplicationVersionDescription> versionIterator=appVersionList.listIterator();
  String curVersionLabel=d.getVersionLabel();
  while (versionIterator.hasNext()) {
    ApplicationVersionDescription versionDescription=versionIterator.next();
    String versionLabel=versionDescription.getVersionLabel();
    if (curVersionLabel.equals(versionLabel) && versionIterator.hasNext()) {
      return changeToVersion(d,versionIterator.next());
    }
  }
  throw new MojoFailureException("No previous version was found (current version: " + curVersionLabel);
}
 

Example 51

From project BeeQueue, under directory /src/org/beequeue/piles/.

Source file: Piles.java

  15 
vote

public static <T>Integer find(List<T> list,T toSearchFor,Comparator<T> compare){
  if (compare == null) {
    compare=new Comparator<T>(){
      public int compare(      T o1,      T o2){
        return o1.equals(o2) ? 0 : -1;
      }
    }
;
  }
  for (int i=0; i < list.size(); i++) {
    if (compare.compare(toSearchFor,list.get(i)) == 0) {
      return i;
    }
  }
  return null;
}
 

Example 52

From project Betfair-Trickle, under directory /src/main/java/uk/co/onehp/trickle/dao/.

Source file: HibernateBetDao.java

  15 
vote

@Override public Bet getNextBet(){
  List<Bet> bets=incompleteBets();
  Collections.sort(bets,new Comparator<Bet>(){
    @Override public int compare(    Bet o1,    Bet o2){
      int mostSeconds1=DateUtil.getMostSeconds(o1.getUnprocessedTimings());
      int mostSeconds2=DateUtil.getMostSeconds(o2.getUnprocessedTimings());
      return o1.getHorse().getRace().getStartTime().minusSeconds(mostSeconds1).compareTo(o2.getHorse().getRace().getStartTime().minusSeconds(mostSeconds2));
    }
  }
);
  return bets.size() > 0 ? bets.get(0) : null;
}
 

Example 53

From project BetterShop_1, under directory /src/me/jascotty2/lib/bukkit/.

Source file: FTP_PluginTracker.java

  15 
vote

public static boolean sendReport(Server server) throws Exception {
  if (server == null) {
    return false;
  }
  String fn="data/" + Info.serverUID();
  List<String> pluginLst=Arrays.asList(installedPlugins(server));
  Collections.sort(pluginLst,new Comparator<String>(){
    public int compare(    String o1,    String o2){
      return o1.compareToIgnoreCase(o2);
    }
  }
);
  StringBuilder plugins=new StringBuilder("\n\t");
  for (  String p : pluginLst) {
    plugins.append(p).append("\n\t");
  }
  String allplugins=plugins.substring(0,plugins.length() - 2);
  int numWorlds=server.getWorlds().size();
  File serverFolder=new File(".").getParentFile();
  ArrayList<String> players=new ArrayList<String>();
  for (  World w : server.getWorlds()) {
    if (w == null) {
      continue;
    }
    File plFolder=new File(serverFolder,w.getName() + File.separator + "players");
    if (plFolder.exists()) {
      for (      File f : plFolder.listFiles()) {
        if (f.getName().toLowerCase().endsWith(".dat") && !players.contains(f.getName())) {
          players.add(f.getName());
        }
      }
    }
  }
  return uploader.SendNewText(fn,"Machine: " + System.getProperty("os.name") + " "+ System.getProperty("os.arch")+ "\n"+ (players.size() > 0 ? "Players: " + players.size() + "\n" : "")+ "Bukkit: "+ server.getVersion()+ "\n"+ "Worlds: "+ numWorlds+ "\n"+ "Plugins ("+ pluginLst.size()+ ") "+ allplugins);
}
 

Example 54

From project BibleQuote-for-Android, under directory /src/com/BibleQuote/widget/.

Source file: ItemAdapter.java

  15 
vote

/** 
 * Sorts the content of this adapter using the specified comparator.
 * @param comparator The comparator used to sort the objects contained inthis adapter.
 */
public void sort(Comparator<? super Item> comparator){
  Collections.sort(mItems,comparator);
  if (mNotifyOnChange) {
    notifyDataSetChanged();
  }
}
 

Example 55

From project BlameSubversion-plugin, under directory /src/main/java/hudson/scm/.

Source file: BlameSubversionChangeLogSet.java

  15 
vote

BlameSubversionChangeLogSet(AbstractBuild build,List<LogEntry> logs){
  super(build);
  Collections.sort(logs,new Comparator<LogEntry>(){
    public int compare(    LogEntry a,    LogEntry b){
      return b.getRevision() - a.getRevision();
    }
  }
);
  this.logs=Collections.unmodifiableList(logs);
  for (  LogEntry log : logs)   log.setParent(this);
}
 

Example 56

From project Blitz, under directory /src/com/laxser/blitz/lama/provider/jdbc/.

Source file: JdbcDataAccessProvider.java

  15 
vote

/** 
 * findPlugin<br>
 * @return
 * @author [email protected] May 26, 2010 - 4:30:09 PM
 */
protected JdbcWrapper[] findJdbcWrappers(){
  @SuppressWarnings("unchecked") Collection<JdbcWrapper> jdbcWrappers=this.applicationContext.getBeansOfType(JdbcWrapper.class).values();
  JdbcWrapper[] arrayJdbcWrappers=jdbcWrappers.toArray(new JdbcWrapper[0]);
  for (  JdbcWrapper jdbcWrapper : arrayJdbcWrappers) {
    Assert.isNull(jdbcWrapper.getJdbc());
  }
  Arrays.sort(arrayJdbcWrappers,new Comparator<JdbcWrapper>(){
    @Override public int compare(    JdbcWrapper thees,    JdbcWrapper that){
      Order thessOrder=thees.getClass().getAnnotation(Order.class);
      Order thatOrder=that.getClass().getAnnotation(Order.class);
      int thessValue=thessOrder == null ? 0 : thessOrder.value();
      int thatValue=thatOrder == null ? 0 : thatOrder.value();
      return thessValue - thatValue;
    }
  }
);
  return arrayJdbcWrappers;
}
 

Example 57

From project blogActivity, under directory /src/com/slezica/tools/widget/.

Source file: FilterableAdapter.java

  15 
vote

public void sort(Comparator<? super ObjectType> comparator){
synchronized (mObjects) {
    Collections.sort(mObjects,comparator);
  }
  if (mNotifyOnChange)   notifyDataSetChanged();
}
 

Example 58

From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/namespace/.

Source file: ComponentDefinitionRegistryImpl.java

  15 
vote

public void registerInterceptorWithComponent(ComponentMetadata component,Interceptor interceptor){
  if (interceptor != null) {
    List<Interceptor> componentInterceptorList=interceptors.get(component);
    if (componentInterceptorList == null) {
      componentInterceptorList=new ArrayList<Interceptor>();
      interceptors.put(component,componentInterceptorList);
    }
    if (!componentInterceptorList.contains(interceptor)) {
      componentInterceptorList.add(interceptor);
      Collections.sort(componentInterceptorList,new Comparator<Interceptor>(){
        public int compare(        Interceptor object1,        Interceptor object2){
          return object2.getRank() - object1.getRank();
        }
      }
);
    }
  }
}
 

Example 59

From project bndtools, under directory /bndtools.core/src/bndtools/editor/completion/.

Source file: BndCompletionProcessor.java

  15 
vote

private static ICompletionProposal[] proposals(String prefix,int offset){
  ArrayList<ICompletionProposal> results=new ArrayList<ICompletionProposal>(Syntax.HELP.size());
  for (  Syntax s : Syntax.HELP.values()) {
    if (prefix == null || s.getHeader().startsWith(prefix)) {
      IContextInformation info=new ContextInformation(s.getHeader(),s.getHeader());
      String text=prefix == null ? s.getHeader() : s.getHeader().substring(prefix.length());
      results.add(new CompletionProposal(text + ": ",offset,0,text.length() + 2,null,s.getHeader(),info,s.getLead()));
    }
  }
  Collections.sort(results,new Comparator<ICompletionProposal>(){
    public int compare(    ICompletionProposal p1,    ICompletionProposal p2){
      return p1.getDisplayString().compareTo(p2.getDisplayString());
    }
  }
);
  return results.toArray(new ICompletionProposal[results.size()]);
}
 

Example 60

From project book, under directory /src/main/java/com/tamingtext/classifier/mlt/.

Source file: CategoryHits.java

  15 
vote

public static Comparator<CategoryHits> comparatorForMode(MatchMode mode){
switch (mode) {
case TFIDF:
    return byScoreComparator();
case KNN:
  return byHitsComparator();
default :
throw new IllegalArgumentException("Unkonwn MatchMode" + mode);
}
}
 

Example 61

From project BookmarksPortlet, under directory /src/main/java/edu/wisc/my/portlets/bookmarks/domain/.

Source file: Folder.java

  15 
vote

/** 
 * @param childComparator The childComparator to set, calls setChildComparator on all children of type Folder.
 */
public void setChildComparator(Comparator<Entry> childComparator){
  if (childComparator == null) {
    throw new IllegalArgumentException("childComparator cannot be null");
  }
  this.childComparator=childComparator;
  if (this.children != null) {
    for (    Map.Entry<Long,Entry> entry : this.children.entrySet()) {
      final Entry child=entry.getValue();
      if (child instanceof Folder) {
        ((Folder)child).setChildComparator(childComparator);
      }
    }
  }
}
 

Example 62

From project BPMN2-Editor-for-Eclipse, under directory /org.eclipse.bpmn2.modeler.core/src/org/eclipse/bpmn2/modeler/core/.

Source file: Bpmn2Preferences.java

  15 
vote

private void sortTools(ArrayList<ToolEnablement> ret){
  Collections.sort(ret,new Comparator<ToolEnablement>(){
    @Override public int compare(    ToolEnablement o1,    ToolEnablement o2){
      return o1.getName().compareToIgnoreCase(o2.getName());
    }
  }
);
}
 

Example 63

From project brix-cms, under directory /brix-core/src/main/java/org/brixcms/plugin/site/folder/.

Source file: FolderDataSource.java

  15 
vote

private void sort(List<BrixNode> original,final String property,final IGridSortState.Direction direction){
  Collections.sort(original,new Comparator<BrixNode>(){
    public int compare(    BrixNode o1,    BrixNode o2){
      int res=compareNodes(o1,o2,property);
      if (direction == IGridSortState.Direction.DESC) {
        res=-res;
      }
      return res;
    }
  }
);
}
 

Example 64

From project brix-cms-plugins, under directory /brix-hierarchical-node-plugin/src/main/java/brix/plugin/hierarchical/folder/.

Source file: FolderDataSource.java

  15 
vote

private void sort(List<BrixNode> original,final String property,final IGridSortState.Direction direction){
  Collections.sort(original,new Comparator<BrixNode>(){
    public int compare(    BrixNode o1,    BrixNode o2){
      int res=compareNodes(o1,o2,property);
      if (direction == IGridSortState.Direction.DESC) {
        res=-res;
      }
      return res;
    }
  }
);
}
 

Example 65

From project brut.apktool, under directory /apktool-lib/src/main/java/brut/androlib/res/data/value/.

Source file: ResFlagsAttr.java

  15 
vote

private void loadFlags(){
  if (mFlags != null) {
    return;
  }
  FlagItem[] zeroFlags=new FlagItem[mItems.length];
  int zeroFlagsCount=0;
  FlagItem[] flags=new FlagItem[mItems.length];
  int flagsCount=0;
  for (int i=0; i < mItems.length; i++) {
    FlagItem item=mItems[i];
    if (item.flag == 0) {
      zeroFlags[zeroFlagsCount++]=item;
    }
 else {
      flags[flagsCount++]=item;
    }
  }
  mZeroFlags=Arrays.copyOf(zeroFlags,zeroFlagsCount);
  mFlags=Arrays.copyOf(flags,flagsCount);
  Arrays.sort(mFlags,new Comparator<FlagItem>(){
    public int compare(    FlagItem o1,    FlagItem o2){
      return Integer.valueOf(Integer.bitCount(o2.flag)).compareTo(Integer.bitCount(o1.flag));
    }
  }
);
}
 

Example 66

From project brut.apktool.smali, under directory /dexlib/src/main/java/org/jf/dexlib/.

Source file: AnnotationSetItem.java

  15 
vote

/** 
 * {@inheritDoc} 
 */
protected void writeItem(AnnotatedOutput out){
  Arrays.sort(annotations,new Comparator<AnnotationItem>(){
    public int compare(    AnnotationItem annotationItem,    AnnotationItem annotationItem2){
      int annotationItemIndex=annotationItem.getEncodedAnnotation().annotationType.getIndex();
      int annotationItemIndex2=annotationItem2.getEncodedAnnotation().annotationType.getIndex();
      if (annotationItemIndex < annotationItemIndex2) {
        return -1;
      }
 else       if (annotationItemIndex == annotationItemIndex2) {
        return 0;
      }
      return 1;
    }
  }
);
  if (out.annotates()) {
    out.annotate(4,"size: 0x" + Integer.toHexString(annotations.length) + " ("+ annotations.length+ ")");
    for (    AnnotationItem annotationItem : annotations) {
      out.annotate(4,"annotation_off: 0x" + Integer.toHexString(annotationItem.getOffset()) + " - "+ annotationItem.getEncodedAnnotation().annotationType.getTypeDescriptor());
    }
  }
  out.writeInt(annotations.length);
  for (  AnnotationItem annotationItem : annotations) {
    out.writeInt(annotationItem.getOffset());
  }
}
 

Example 67

From project bundlemaker, under directory /integrationtest/org.bundlemaker.itest.spring/src/org/bundlemaker/itest/spring/.

Source file: DeleteModuleTransformation.java

  15 
vote

/** 
 * <p> </p>
 * @param sourceResources
 * @return
 */
private List<IResource> getSortedResources(Set<IResource> sourceResources){
  List<IResource> sorted=new LinkedList<IResource>(sourceResources);
  Collections.sort(sorted,new Comparator<IResource>(){
    public int compare(    IResource resource1,    IResource resource2){
      if (!resource1.getRoot().equals(resource2.getRoot())) {
        return resource1.getRoot().compareTo(resource2.getRoot());
      }
      return resource1.getPath().compareTo(resource2.getPath());
    }
  }
);
  return sorted;
}
 

Example 68

From project C-Cat, under directory /util/src/main/java/gov/llnl/ontology/util/.

Source file: Counter.java

  15 
vote

/** 
 * Returns a view of the items currently being counted in sorted order.  The returned view is read-write.
 */
public List<T> itemsSorted(boolean sortAscending){
  Comparator<? super Map.Entry<T,Integer>> comparator=new EntryComparator(sortAscending);
  Set<Map.Entry<T,Integer>> sortedItemSet=new TreeSet<Map.Entry<T,Integer>>(comparator);
  sortedItemSet.addAll(counts.entrySet());
  List<T> items=new ArrayList<T>(counts.size());
  for (  Map.Entry<T,Integer> item : sortedItemSet)   items.add(item.getKey());
  return items;
}
 

Example 69

From project candlepin, under directory /src/main/java/org/candlepin/resource/util/.

Source file: ConsumerInstalledProductEnricher.java

  15 
vote

/** 
 * Return a copy of the specified list of <code>Entitlement</code>s sorted by start date ASC.
 * @param toSort the list to sort.
 * @return
 */
private List<Entitlement> sortByStartDate(List<Entitlement> toSort){
  List<Entitlement> sorted=new ArrayList<Entitlement>(toSort);
  Collections.sort(sorted,new Comparator<Entitlement>(){
    @Override public int compare(    Entitlement ent1,    Entitlement ent2){
      return ent1.getStartDate().compareTo(ent2.getStartDate());
    }
  }
);
  return sorted;
}
 

Example 70

From project capedwarf-blue, under directory /cluster-tests/src/test/java/org/jboss/test/capedwarf/cluster/.

Source file: ProspectiveSearchTestCase.java

  15 
vote

protected void sortBySubId(List<Subscription> subscriptions){
  Collections.sort(subscriptions,new Comparator<Subscription>(){
    public int compare(    Subscription o1,    Subscription o2){
      return o1.getId().compareTo(o2.getId());
    }
  }
);
}
 

Example 71

From project Carolina-Digital-Repository, under directory /persistence/src/main/java/edu/unc/lib/dl/services/.

Source file: BatchIngestQueue.java

  15 
vote

public File[] getFailedDirectories(){
  File[] batchDirs=this.failedDirectory.listFiles(new FileFilter(){
    @Override public boolean accept(    File arg0){
      return arg0.isDirectory();
    }
  }
);
  if (batchDirs != null) {
    Arrays.sort(batchDirs,new Comparator<File>(){
      @Override public int compare(      File o1,      File o2){
        if (o1 == null || o2 == null)         return 0;
        return (int)(o1.lastModified() - o2.lastModified());
      }
    }
);
    return batchDirs;
  }
 else {
    return new File[]{};
  }
}
 

Example 72

From project Catroid-maven-playground, under directory /src/main/java/at/tugraz/ist/catroid/io/.

Source file: CatroidFieldKeySorter.java

  15 
vote

@SuppressWarnings({"unchecked","rawtypes"}) public Map sort(final Class type,final Map keyedByFieldKey){
  final Map map=new TreeMap(new Comparator(){
    public int compare(    final Object o1,    final Object o2){
      final FieldKey fieldKey1=(FieldKey)o1;
      final FieldKey fieldKey2=(FieldKey)o2;
      int i=fieldKey1.getDepth() - fieldKey2.getDepth();
      if (i == 0) {
        String fieldNameOrAlias1=getFieldNameOrAlias(fieldKey1);
        String fieldNameOrAlias2=getFieldNameOrAlias(fieldKey2);
        i=fieldNameOrAlias1.compareTo(fieldNameOrAlias2);
      }
      return i;
    }
  }
);
  map.putAll(keyedByFieldKey);
  return map;
}
 

Example 73

From project ceres, under directory /ceres-core/src/main/java/com/bc/ceres/core/runtime/internal/.

Source file: RuntimeImpl.java

  15 
vote

private void resolveModules(ProgressMonitor pm){
  ModuleImpl[] modules=moduleRegistry.getModules();
  resolvedModules=new ArrayList<ModuleImpl>(modules.length);
  pm.beginTask("Resolving modules",modules.length + 1);
  try {
    for (    ModuleImpl module : modules) {
      resolveModule(module);
      pm.worked(1);
    }
    Collections.sort(resolvedModules,new Comparator<ModuleImpl>(){
      public int compare(      ModuleImpl m1,      ModuleImpl m2){
        return m2.getRefCount() - m1.getRefCount();
      }
    }
);
    pm.worked(1);
    logResolveSummary();
  }
  finally {
    pm.done();
  }
}
 

Example 74

From project ceylon-ide-eclipse, under directory /plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/imports/.

Source file: ImportSelectionDialog.java

  15 
vote

@Override protected Comparator getItemsComparator(){
  return new Comparator<Object>(){
    @Override public int compare(    Object o1,    Object o2){
      Declaration d1=(Declaration)o1;
      Declaration d2=(Declaration)o2;
      return d1.getQualifiedNameString().compareTo(d2.getQualifiedNameString());
    }
  }
;
}