Example usage for java.lang Integer compareTo

List of usage examples for java.lang Integer compareTo

Introduction

In this page you can find the example usage for java.lang Integer compareTo.

Prototype

public int compareTo(Integer anotherInteger) 

Source Link

Document

Compares two Integer objects numerically.

Usage

From source file:org.stem.db.MountPoint.java

public Collection<FatFile> findBlankOrActive() {
    Collection<FatFile> collection = CollectionUtils.select(fatFiles.values(), new Predicate<FatFile>() {
        @Override//from www . j  a v a 2 s  .com
        public boolean evaluate(FatFile file) {
            return file.isBlank() || file.isActive();
        }
    });

    List<FatFile> sortedList = new ArrayList<FatFile>(collection);

    // Sort, ACTIVE files is placed first
    Collections.sort(sortedList, new Comparator<FatFile>() {
        @Override
        public int compare(FatFile f1, FatFile f2) {
            if (f1.getState() == f2.getState())
                return f1.id.compareTo(f2.id);

            else {
                Integer state1 = f1.getState().ordinal();
                Integer state2 = f2.getState().ordinal();
                return state1.compareTo(state2);
            }
        }
    });

    return sortedList;
}

From source file:org.kuali.kfs.gl.businessobject.CorrectionCriteria.java

/**
 * Compares this object with another CorrectionCriteria based on document number, 
 * correction change group line number, and correction criteria line number
 * /*from www. j a v  a 2 s .c  om*/
 * @see java.lang.Comparable#compareTo(java.lang.Object)
 */
public int compareTo(Object o) {
    CorrectionCriteria cc = (CorrectionCriteria) o;

    String thisFdocNbr = documentNumber == null ? "" : documentNumber;
    String thatFdocNbr = cc.documentNumber == null ? "" : cc.documentNumber;
    int c = thisFdocNbr.compareTo(thatFdocNbr);

    if (c == 0) {
        Integer thisGn = correctionChangeGroupLineNumber == null ? 0 : correctionChangeGroupLineNumber;
        Integer thatGn = cc.correctionChangeGroupLineNumber == null ? 0 : cc.correctionChangeGroupLineNumber;
        c = thisGn.compareTo(thatGn);
        if (c == 0) {
            Integer thisCln = correctionCriteriaLineNumber == null ? 0 : correctionCriteriaLineNumber;
            Integer thatCln = correctionCriteriaLineNumber == null ? 0 : cc.correctionCriteriaLineNumber;
            return c = thisCln.compareTo(thatCln);
        } else {
            return c;
        }
    } else {
        return c;
    }
}

From source file:org.forgerock.openidm.shell.CustomCommandScope.java

/**
 * Fetches a sorted list of methods all sharing a specified name.
 * This list is returned in increasing order of parameters.
 * @param name the name of the method list to retrieve
 * @return a sorted list of methods//from w  ww.j  av  a  2  s  .  co  m
 */
protected List<Method> getAllMethodsByName(String name) {
    Method[] allMethods = this.getClass().getDeclaredMethods();
    List<Method> allNamedMethods = new ArrayList<Method>();
    for (Method m : allMethods) {
        if (m.getName().equals(name)) {
            allNamedMethods.add(m);
        }
    }

    Collections.sort(allNamedMethods, new Comparator<Method>() {
        public int compare(Method o1, Method o2) {
            Integer l1 = o1.getParameterTypes().length;
            Integer l2 = o2.getParameterTypes().length;
            return l1.compareTo(l2);
        }
    });

    return allNamedMethods;
}

From source file:edu.mit.mobile.android.appupdater.AppUpdateChecker.java

@SuppressWarnings("unchecked")
private void triggerFromJson(JSONObject jo) throws JSONException {

    final ArrayList<String> changelog = new ArrayList<String>();

    // keep a sorted map of versionCode to the version information objects.
    // Most recent is at the top.
    final TreeMap<Integer, JSONObject> versionMap = new TreeMap<Integer, JSONObject>(new Comparator<Integer>() {
        public int compare(Integer object1, Integer object2) {
            return object2.compareTo(object1);
        };//from  w  w w  .  ja v  a2s.c o m
    });

    for (final Iterator<String> i = jo.keys(); i.hasNext();) {
        final String versionName = i.next();
        if (versionName.equals("package")) {
            pkgInfo = jo.getJSONObject(versionName);
            continue;
        }
        final JSONObject versionInfo = jo.getJSONObject(versionName);
        versionInfo.put("versionName", versionName);

        final int versionCode = versionInfo.getInt("versionCode");
        versionMap.put(versionCode, versionInfo);
    }
    final int latestVersionNumber = versionMap.firstKey();
    final String latestVersionName = versionMap.get(latestVersionNumber).getString("versionName");
    final Uri downloadUri = Uri.parse(pkgInfo.getString("downloadUrl"));

    if (currentAppVersion > latestVersionNumber) {
        Log.d(TAG, "We're newer than the latest published version (" + latestVersionName
                + "). Living in the future...");
        mUpdateListener.appUpdateStatus(true, latestVersionName, null, downloadUri);
        return;
    }

    if (currentAppVersion == latestVersionNumber) {
        Log.d(TAG, "We're at the latest version (" + currentAppVersion + ")");
        mUpdateListener.appUpdateStatus(true, latestVersionName, null, downloadUri);
        return;
    }

    // construct the changelog. Newest entries are at the top.
    for (final Entry<Integer, JSONObject> version : versionMap.headMap(currentAppVersion).entrySet()) {
        final JSONObject versionInfo = version.getValue();
        final JSONArray versionChangelog = versionInfo.optJSONArray("changelog");
        if (versionChangelog != null) {
            final int len = versionChangelog.length();
            for (int i = 0; i < len; i++) {
                changelog.add(versionChangelog.getString(i));
            }
        }
    }

    mUpdateListener.appUpdateStatus(false, latestVersionName, changelog, downloadUri);
}

From source file:ome.services.search.FullText.java

@Transactional(readOnly = true)
public Object doWork(Session s, ServiceFactory sf) {

    final Class<?> cls = values.onlyTypes.get(0);

    FullTextSession session = Search.getFullTextSession(s);
    Criteria criteria = session.createCriteria(cls);
    AnnotationCriteria ann = new AnnotationCriteria(criteria, values.fetchAnnotations);

    ids(criteria);//from www . j  a v  a 2  s .c om
    ownerOrGroup(cls, criteria);
    createdOrModified(cls, criteria);
    annotatedBy(ann);
    annotatedBetween(ann);

    // annotatedWith
    if (values.onlyAnnotatedWith != null) {
        if (values.onlyAnnotatedWith.size() > 1) {
            throw new ApiUsageException("HHH-879: " + "At the moment Hibernate cannot fulfill this request.\n"
                    + "Please use only a single onlyAnnotatedWith "
                    + "parameter when performing full text searches.");
        } else if (values.onlyAnnotatedWith.size() > 0) {
            if (!IAnnotated.class.isAssignableFrom(cls)) {
                // A non-IAnnotated object cannot have any
                // Annotations, and so our results are null
                return null; // EARLY EXIT !
            } else {
                for (Class<?> annCls : values.onlyAnnotatedWith) {
                    SimpleExpression ofType = new TypeEqualityExpression("class", annCls);
                    ann.getChild().add(ofType);
                }
            }
        } else {
            criteria.add(Restrictions.isEmpty("annotationLinks"));
        }
    }

    // orderBy
    if (values.orderBy.size() > 0) {
        for (int i = 0; i < values.orderBy.size(); i++) {
            String orderBy = values.orderBy.get(i);
            String orderWithoutMode = orderByPath(orderBy);
            boolean ascending = orderByAscending(orderBy);
            if (ascending) {
                criteria.addOrder(Order.asc(orderWithoutMode));
            } else {
                criteria.addOrder(Order.desc(orderWithoutMode));
            }
        }
    }

    final String ticket975 = "ticket:975 - Wrong return type: %s instead of %s\n"
            + "Under some circumstances, byFullText and related methods \n"
            + "like bySomeMustNone can return instances of the wrong \n"
            + "types. One known case is the use of onlyAnnotatedWith(). \n"
            + "If you are recieving this error, please try using the \n"
            + "intersection/union methods to achieve the same results.";

    // Main query
    FullTextQuery ftQuery = session.createFullTextQuery(this.q, cls);
    ftQuery.setProjection(ProjectionConstants.SCORE, ProjectionConstants.ID);
    List<?> result = ftQuery.list();
    int totalSize = ftQuery.getResultSize();

    if (result.size() == 0) {
        // EARLY EXIT 
        return result; // of wrong type but with generics it doesn't matter
    }

    final Map<Long, Integer> order = new HashMap<Long, Integer>();
    final Map<Long, Float> scores = new HashMap<Long, Float>();
    for (int i = 0; i < result.size(); i++) {
        Object[] parts = (Object[]) result.get(i);
        scores.put((Long) parts[1], (Float) parts[0]);
        order.put((Long) parts[1], i);
    }

    // TODO Could add a performance optimization here on returnUnloaded

    criteria.add(Restrictions.in("id", scores.keySet()));
    final List<IObject> check975 = criteria.list();
    for (IObject object : check975) {
        // TODO This is now all but impossible. Remove
        if (!cls.isAssignableFrom(object.getClass())) {
            throw new ApiUsageException(String.format(ticket975, object.getClass(), cls));
        } else {
            object.putAt("TOTAL_SIZE", totalSize);
            object.putAt(ProjectionConstants.SCORE, scores.get(object.getId()));
        }
    }

    // Order return value based on the original ordering

    final Comparator cmp = new Comparator() {
        public int compare(Object obj1, Object obj2) {
            IObject o1 = (IObject) obj1;
            IObject o2 = (IObject) obj2;
            Long id1 = o1.getId();
            Long id2 = o2.getId();
            Integer idx1 = order.get(id1);
            Integer idx2 = order.get(id2);
            return idx1.compareTo(idx2);
        }
    };
    Collections.sort(check975, cmp);
    return check975;
}

From source file:org.betaconceptframework.astroboa.commons.comparator.ContentObjectFolderComparator.java

public int compare(ContentObjectFolder folder1, ContentObjectFolder folder2) {

    if (folder1 == null)
        return -1;

    if (folder2 == null)
        return 1;

    if (folder1.getType() != folder2.getType()) {
        logger.warn("Unable to compare content object folders with different types {} , {}", folder1.getType(),
                folder2.getType());/*w  ww .j av  a2  s.com*/
        return 0;
    }

    try {

        String folderLabel1 = folder1.getLocalizedLabelForCurrentLocale();
        String folderLabel2 = folder2.getLocalizedLabelForCurrentLocale();

        if (folderLabel1 == null && folderLabel2 == null)
            return 0;

        if (folderLabel1 != null && folderLabel2 == null)
            return 1;

        if (folderLabel1 == null && folderLabel2 != null)
            return -1;

        //Both folders should have the same type
        switch (folder1.getType()) {
        case SECOND:
        case MINUTE:
        case HOUR:
        case DAY:
        case MONTH:
        case YEAR:
            //Labels for MINUTE, HOUR, DAY, MONTH and YEAR are numbers
            Integer folderLabelInt1 = Integer.parseInt(folderLabel1);
            Integer folderLabelInt2 = Integer.parseInt(folderLabel2);

            //If type is YEAR, inverse compare as years must be displayed in descending order
            if (Type.YEAR == folder1.getType())
                return folderLabelInt2.compareTo(folderLabelInt1);

            return folderLabelInt1.compareTo(folderLabelInt2);

        case CONTENT_TYPE:
            if ("el".equalsIgnoreCase(locale)) {
                //Filter string to lower case and transforming accented characters to simple ones
                String lowerCaseGreekFilteredLocalizedLabel0 = CmsUtils.filterGreekCharacters(folderLabel1);
                String lowerCaseGreekFilteredLocalizedLabel1 = CmsUtils.filterGreekCharacters(folderLabel2);

                return lowerCaseGreekFilteredLocalizedLabel0.compareTo(lowerCaseGreekFilteredLocalizedLabel1);
            } else
                return folderLabel1.compareTo(folderLabel2);
        default:
            return 0;
        }

    } catch (Exception e) {
        logger.error("While comparing content object folders ", e);
        return 0;
    }

}

From source file:org.trnltk.apps.tokenizer.UniqueWordFinderApp.java

@App("Goes thru tokenized files, finds unique words")
public void findWordHistogram() throws InterruptedException {
    final StopWatch taskStopWatch = new StopWatch();
    taskStopWatch.start();/*from  w w  w  .  j a va2 s  .co  m*/

    final File parentFolder = new File("D:\\devl\\data\\aakindan");
    final File sourceFolder = new File(parentFolder, "src_split_tokenized");
    final File[] files = sourceFolder.listFiles();
    Validate.notNull(files);

    final List<File> filesToRead = new ArrayList<File>();
    for (File file : files) {
        if (file.isDirectory())
            continue;

        filesToRead.add(file);
    }

    int NUMBER_OF_THREADS = 8;
    final ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(NUMBER_OF_THREADS);
    Map[] countMaps = new Map[NUMBER_OF_THREADS];
    for (int i = 0; i < countMaps.length; i++) {
        countMaps[i] = new HashMap(1000000);
    }

    for (int i = 0; i < filesToRead.size(); i++) {
        File file = filesToRead.get(i);
        //noinspection unchecked
        pool.execute(new HistogramCommand(countMaps[i % NUMBER_OF_THREADS], file));
    }

    pool.shutdown();
    while (!pool.isTerminated()) {
        //System.out.println("Waiting pool to be terminated!");
        pool.awaitTermination(3000, TimeUnit.MILLISECONDS);
    }

    System.out.println("Merging countMaps");
    final HashMap<String, Integer> mergeMap = new HashMap<String, Integer>(
            countMaps[0].size() * NUMBER_OF_THREADS); //approx
    for (Map<String, Integer> countMap : countMaps) {
        for (Map.Entry<String, Integer> stringIntegerEntry : countMap.entrySet()) {
            final String surface = stringIntegerEntry.getKey();
            final Integer newCount = stringIntegerEntry.getValue();
            final Integer existingCount = mergeMap.get(surface);
            if (existingCount == null)
                mergeMap.put(surface, newCount);
            else
                mergeMap.put(surface, existingCount + newCount);
        }
    }

    System.out.println("Sorting mergeMaps");
    final Map<String, Integer> sortedMergeMap = new TreeMap<String, Integer>(new Comparator<String>() {
        @Override
        public int compare(String a, String b) {
            Integer x = mergeMap.get(a);
            Integer y = mergeMap.get(b);
            if (x.equals(y)) {
                return a.compareTo(b);
            }
            return y.compareTo(x);
        }
    });

    sortedMergeMap.putAll(mergeMap);

    System.out.println("Writing to file");
    int numberOfTokens = 0;
    final File outputFile = new File(parentFolder, "wordHistogram.txt");
    BufferedWriter bufferedWriter = null;
    try {
        bufferedWriter = Files.newWriter(outputFile, Charsets.UTF_8);
        for (Map.Entry<String, Integer> entry : sortedMergeMap.entrySet()) {
            numberOfTokens += entry.getValue();
            bufferedWriter.write(entry.getKey() + " " + entry.getValue() + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bufferedWriter != null)
            try {
                bufferedWriter.close();
            } catch (IOException e) {
                System.err.println("Unable to close file ");
                e.printStackTrace();
            }
    }

    taskStopWatch.stop();

    System.out.println("Total time :" + taskStopWatch.toString());
    System.out.println("Nr of tokens : " + numberOfTokens);
    System.out.println("Nr of unique tokens : " + sortedMergeMap.size());
}

From source file:com.manydesigns.elements.reflection.JavaClassAccessor.java

protected List<PropertyAccessor> setupKeyPropertyAccessors() {
    Map<String, List<PropertyAccessor>> keys = new HashMap<String, List<PropertyAccessor>>();
    for (PropertyAccessor propertyAccessor : propertyAccessors) {
        Key key = propertyAccessor.getAnnotation(Key.class);
        if (key != null) {
            List<PropertyAccessor> keyProperties = keys.get(key.name());
            if (keyProperties == null) {
                keyProperties = new ArrayList<PropertyAccessor>();
                keys.put(key.name(), keyProperties);
            }// w w  w.  j  a v a 2  s  .com
            keyProperties.add(propertyAccessor);
        }
    }

    if (keys.isEmpty()) {
        logger.debug("No primary key configured for {}", javaClass);
        return Collections.emptyList();
    }

    String primaryKeyName;
    List<PropertyAccessor> keyAccessors;
    Key key = getAnnotation(Key.class);
    if (key != null) {
        primaryKeyName = key.name();
    } else {
        primaryKeyName = Key.DEFAULT_NAME;
    }
    keyAccessors = keys.get(primaryKeyName);
    if (keyAccessors == null) {
        keyAccessors = keys.get(Key.DEFAULT_NAME);
    }
    if (keyAccessors == null) {
        logger.debug("Primary key \"" + primaryKeyName + "\" not found in " + javaClass
                + "; using the first available key.");
        keyAccessors = keys.values().iterator().next();
    }

    Collections.sort(keyAccessors, new Comparator<PropertyAccessor>() {
        public int compare(PropertyAccessor o1, PropertyAccessor o2) {
            Integer ord1 = o1.getAnnotation(Key.class).order();
            Integer ord2 = o2.getAnnotation(Key.class).order();
            return ord1.compareTo(ord2);
        }
    });

    return keyAccessors;
}

From source file:org.intermine.bio.dataconversion.EntrezOrganismRetriever.java

/**
 * For each Organism in the objectstore, retreive it's details from entrez using the taxon and
 * fill in the details in the organism object.
 * @throws BuildException if an error occurs
 *///from ww  w . j  a  v  a2  s  .c o m
public void execute() {
    // Needed so that STAX can find it's implementation classes
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());

    if (osAlias == null) {
        throw new BuildException("osAlias attribute is not set");
    }
    if (outputFile == null) {
        throw new BuildException("outputFile attribute is not set");
    }

    LOG.info("Starting EntrezOrganismRetriever");

    Writer writer = null;

    try {
        writer = new FileWriter(outputFile);

        ObjectStore os = ObjectStoreFactory.getObjectStore(osAlias);

        Map<Integer, Organism> orgMap = getOrganisms(os);

        Set<Integer> taxonIds = new HashSet<Integer>();
        Set<Item> toStore = new HashSet<Item>();

        ItemFactory itemFactory = new ItemFactory(os.getModel(), "-1_");
        writer.write(FullRenderer.getHeader() + "\n");
        for (Iterator<Integer> i = orgMap.keySet().iterator(); i.hasNext();) {
            Integer taxonId = i.next();
            if (taxonId == null || !(taxonId.compareTo(0) > 0)) {
                continue;
            }
            taxonIds.add(taxonId);
            if (taxonIds.size() == BATCH_SIZE || !i.hasNext()) {
                SAXParser.parse(new InputSource(getReader(taxonIds)), new Handler(toStore, itemFactory), false);
                for (Iterator<Item> j = toStore.iterator(); j.hasNext();) {
                    Item item = j.next();
                    writer.write(FullRenderer.render(item));
                }
                taxonIds.clear();
                toStore.clear();
            }
        }
        writer.write(FullRenderer.getFooter() + "\n");
    } catch (Exception e) {
        throw new BuildException("exception while retrieving organisms", e);
    } finally {
        Thread.currentThread().setContextClassLoader(cl);
        if (writer != null) {
            try {
                writer.close();
            } catch (Exception e) {
                // ignore
            }
        }
    }
}

From source file:org.wikipedia.vlsergey.secretary.books.CountBooks.java

@Override
public void run() {
    final Map<String, TLongSet> byISBN = new HashMap<String, TLongSet>();
    final Map<String, TLongSet> byAuthor = new HashMap<String, TLongSet>();
    final Map<String, TLongSet> byBookTitle = new HashMap<String, TLongSet>();

    // for (Revision revision :
    // wikiCache.queryLatestContentByPageIds(mediaWikiBot.queryEmbeddedInPageIds(
    // "Template:", Namespaces.MAIN))) {

    for (Revision revision : wikiCache.queryByEmbeddedIn("Template:",
            new Namespace[] { Namespace.MAIN })) {

        final Page page = revision.getPage();
        final String title = page.getTitle();
        try {//from   w ww  .  j a  v  a2s  .  c o  m
            final String xmlContent = revision.getXml();
            {
                final String lowerCaseXml = xmlContent.toLowerCase();
                if (!lowerCaseXml.contains("") && !lowerCaseXml.contains("cite book")) {
                    continue;
                }
            }

            ArticleFragment article = mediaWikiBot.getXmlParser().parse(revision);

            Map<String, List<Template>> allTemplates = article.getAllTemplates();

            if (allTemplates.containsKey("")) {
                for (Template template : allTemplates.get("")) {
                    addISBN(byISBN, page, title, template.getParameterValue("isbn"));
                    addAuthor(byAuthor, page, title, template.getParameterValue(""));
                    addBookTitle(byBookTitle, page, title, template.getParameterValue(""));
                }
            }

            if (allTemplates.containsKey("cite book")) {
                for (Template template : allTemplates.get("cite book")) {
                    addISBN(byISBN, page, title, template.getParameterValue("id"));
                    addISBN(byISBN, page, title, template.getParameterValue("isbn"));
                    addBookTitle(byBookTitle, page, title, template.getParameterValue("title"));
                }
            }
        } catch (Exception exc) {
            log.warn(title + ": " + exc.getMessage());
        }

    }

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("__TOC__\n");

    {
        stringBuilder.append("== By ISBN ==\n");
        List<String> isbns = new ArrayList<String>(byISBN.keySet());
        Collections.sort(isbns, new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                Integer i1 = byISBN.get(o1).size();
                Integer i2 = byISBN.get(o2).size();
                return i2.compareTo(i1);
            }

        });

        for (String isbn : isbns) {
            int count = byISBN.get(isbn).size();
            if (count < 10)
                break;
            stringBuilder.append("* ISBN " + isbn + "  " + count + " articles\n");
        }
    }

    {
        stringBuilder.append("== By author ==\n");
        List<String> authors = new ArrayList<String>(byAuthor.keySet());
        Collections.sort(authors, new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                Integer i1 = byAuthor.get(o1).size();
                Integer i2 = byAuthor.get(o2).size();
                return i2.compareTo(i1);
            }

        });

        for (String author : authors) {
            int count = byAuthor.get(author).size();
            if (count < 10)
                break;
            stringBuilder.append("* " + author + "  " + count + " articles\n");
        }
    }

    {
        stringBuilder.append("== By title ==\n");
        List<String> bookTitles = new ArrayList<String>(byBookTitle.keySet());
        Collections.sort(bookTitles, new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                Integer i1 = byBookTitle.get(o1).size();
                Integer i2 = byBookTitle.get(o2).size();
                return i2.compareTo(i1);
            }

        });

        for (String bookTitle : bookTitles) {
            int count = byBookTitle.get(bookTitle).size();
            if (count < 10)
                break;
            stringBuilder.append("* " + bookTitle + "  " + count + " articles\n");
        }
    }

    mediaWikiBot.writeContent("User:" + mediaWikiBot.getLogin() + "/CountBooks", null, stringBuilder.toString(),
            null, "Update most used books", true, false);
}