Example usage for java.lang Integer compare

List of usage examples for java.lang Integer compare

Introduction

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

Prototype

public static int compare(int x, int y) 

Source Link

Document

Compares two int values numerically.

Usage

From source file:edu.usc.ir.geo.gazetteer.GeoNameResolver.java

/**
 * Select the best match for each location name extracted from a document,
 * choosing from among a list of lists of candidate matches. Filter uses the
 * following features: 1) edit distance between name and the resolved name,
 * choose smallest one 2) content (haven't implemented)
 *
 * @param resolvedEntities//from   w  ww .  j a  v  a2s .  com
 *            final result for the input stream
 * @param allCandidates
 *            each location name may hits several documents, this is the
 *            collection for all hitted documents
 * @param count
 *            Number of results for one locations
 * @throws IOException
 * @throws RuntimeException
 */

private void pickBestCandidates(HashMap<String, List<Location>> resolvedEntities,
        HashMap<String, List<Location>> allCandidates, int count) {

    for (String extractedName : allCandidates.keySet()) {

        List<Location> cur = allCandidates.get(extractedName);
        if (cur.isEmpty())
            continue;//continue if no results found

        int maxWeight = Integer.MIN_VALUE;
        //In case weight is equal for all return top element
        int bestIndex = 0;
        //Priority queue to return top elements
        PriorityQueue<Location> pq = new PriorityQueue<>(cur.size(), new Comparator<Location>() {
            @Override
            public int compare(Location o1, Location o2) {
                return Integer.compare(o2.getWeight(), o1.getWeight());
            }
        });

        for (int i = 0; i < cur.size(); ++i) {
            int weight = 0;
            // get cur's ith resolved entry's name
            String resolvedName = String.format(" %s ", cur.get(i).getName());
            if (resolvedName.contains(String.format(" %s ", extractedName))) {
                // Assign a weight as per configuration if extracted name is found as a exact word in name
                weight = WEIGHT_NAME_MATCH;
            } else if (resolvedName.contains(extractedName)) {
                // Assign a weight as per configuration if extracted name is found partly in name
                weight = WEIGHT_NAME_PART_MATCH;
            }
            // get all alternate names of cur's ith resolved entry's
            String[] altNames = cur.get(i).getAlternateNames().split(",");
            float altEditDist = 0;
            for (String altName : altNames) {
                if (altName.contains(extractedName)) {
                    altEditDist += StringUtils.getLevenshteinDistance(extractedName, altName);
                }
            }
            //lesser the edit distance more should be the weight
            weight += getCalibratedWeight(altNames.length, altEditDist);

            //Give preference to sorted results. 0th result should have more priority
            weight += (cur.size() - i) * WEIGHT_SORT_ORDER;

            cur.get(i).setWeight(weight);

            if (weight > maxWeight) {
                maxWeight = weight;
                bestIndex = i;
            }

            pq.add(cur.get(i));
        }
        if (bestIndex == -1)
            continue;

        List<Location> resultList = new ArrayList<>();

        for (int i = 0; i < count && !pq.isEmpty(); i++) {
            resultList.add(pq.poll());
        }

        resolvedEntities.put(extractedName, resultList);
    }
}

From source file:org.search.niem.uml.merge.DiagramSynchronizer.java

private void createContentsIfNecessary(final View theElementView) {
    final EObject theElement = theElementView.getElement();
    final EList<Property> ownedAttributes = asEList(getOwnedAttributes(theElement));
    if (!ownedAttributes.isEmpty()) {
        final View theOwnedAttributeCompartment = getTheAttributeCompartment(theElementView);
        for (final Property p : ownedAttributes) {
            getOrCreateTheView(p, theOwnedAttributeCompartment);
        }/* w w  w. j  ava 2 s  .  com*/
        @SuppressWarnings("unchecked")
        final EList<View> attributeViews = theOwnedAttributeCompartment.getPersistedChildren();
        ECollections.sort(attributeViews, new Comparator<View>() {
            @Override
            public int compare(final View left, final View right) {
                return Integer.compare(indexOf(ownedAttributes, left.getElement(), 0),
                        indexOf(ownedAttributes, right.getElement(), 0));
            }
        });
    }
    for (final Generalization g : getGeneralizations(theElement)) {
        getOrCreateTheView(g, theElementView.getDiagram());
    }
}

From source file:org.deeplearning4j.arbiter.optimize.ui.ArbiterUIServer.java

public void updateResults(Collection<CandidateStatus> status) {
    List<CandidateStatus> list = new ArrayList<>(status);
    Collections.sort(list, new Comparator<CandidateStatus>() {
        @Override/*  ww w  .  j a  va2  s .c o  m*/
        public int compare(CandidateStatus o1, CandidateStatus o2) {
            return Integer.compare(o1.getIndex(), o2.getIndex());
        }
    });

    //Post update:
    if (targetResultsUpdate == null)
        targetResultsUpdate = client.target("http://localhost:" + port + "/results/update");
    targetResultsUpdate.request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)
            .post(Entity.entity(list, MediaType.APPLICATION_JSON));
    log.trace("Posted new results: {}", list);
    lastResultsUpdateTime.set(System.currentTimeMillis());

    updateStatusTimes();
}

From source file:com.github.sevntu.checkstyle.ordering.MethodOrder.java

private static List<Method> getInitialMethodOrdering(Map<String, Method> methods) {
    return methods.values().stream()
            .sorted((lhs, rhs) -> Integer.compare(lhs.getInitialIndex(), rhs.getInitialIndex()))
            .collect(Collectors.toList());
}

From source file:com.evolveum.midpoint.web.component.prism.ContainerValueWrapper.java

public void sort() {
    Locale locale = WebModelServiceUtils.getLocale();
    if (locale == null) {
        locale = Locale.getDefault();
    }/*from   w  w w. j  a va  2  s. c  o m*/
    Collator collator = Collator.getInstance(locale);
    if (isSorted()) {
        collator.setStrength(Collator.SECONDARY); // e.g. "a" should be different from ""
        collator.setDecomposition(Collator.FULL_DECOMPOSITION); // slower but more precise

        Collections.sort(properties, new Comparator<ItemWrapper>() {
            @Override
            public int compare(ItemWrapper pw1, ItemWrapper pw2) {

                if (pw1 instanceof ContainerWrapper) {
                    ((ContainerWrapper) pw1).sort();
                }

                if (pw2 instanceof ContainerWrapper) {
                    ((ContainerWrapper) pw2).sort();
                }

                if (PropertyOrReferenceWrapper.class.isAssignableFrom(pw1.getClass())
                        && pw2 instanceof ContainerWrapper) {
                    return -1;
                }

                if (PropertyOrReferenceWrapper.class.isAssignableFrom(pw2.getClass())
                        && pw1 instanceof ContainerWrapper) {
                    return 1;
                }
                //               
                return compareByDisplayNames(pw1, pw2, collator);
            }
        });
    } else {
        Collections.sort(properties, new Comparator<ItemWrapper>() {
            @Override
            public int compare(ItemWrapper pw1, ItemWrapper pw2) {

                if (pw1 instanceof ContainerWrapper) {
                    ((ContainerWrapper) pw1).sort();
                }

                if (pw2 instanceof ContainerWrapper) {
                    ((ContainerWrapper) pw2).sort();
                }

                if (PropertyOrReferenceWrapper.class.isAssignableFrom(pw1.getClass())
                        && pw2 instanceof ContainerWrapper) {
                    return -1;
                }

                if (PropertyOrReferenceWrapper.class.isAssignableFrom(pw2.getClass())
                        && pw1 instanceof ContainerWrapper) {
                    return 1;
                }

                ItemDefinition id1 = pw1.getItemDefinition();
                ItemDefinition id2 = pw2.getItemDefinition();

                int displayOrder1 = (id1 == null || id1.getDisplayOrder() == null) ? Integer.MAX_VALUE
                        : id1.getDisplayOrder();
                int displayOrder2 = (id2 == null || id2.getDisplayOrder() == null) ? Integer.MAX_VALUE
                        : id2.getDisplayOrder();
                if (displayOrder1 == displayOrder2) {
                    return compareByDisplayNames(pw1, pw2, collator);
                } else {
                    return Integer.compare(displayOrder1, displayOrder2);
                }
            }
        });
    }

}

From source file:de.tudarmstadt.ukp.dariah.IO.DARIAHWriter.java

private void convert(JCas aJCas, PrintWriter aOut) {
    int paragraphId = 0, sentenceId = 0, tokenId = 0;

    Map<Token, Collection<NamedEntity>> neCoveringMap = JCasUtil.indexCovering(aJCas, Token.class,
            NamedEntity.class);
    Map<Token, Collection<Chunk>> chunksCoveringMap = JCasUtil.indexCovering(aJCas, Token.class, Chunk.class);

    Map<Token, Collection<Section>> sectionCoveringMap = JCasUtil.indexCovering(aJCas, Token.class,
            Section.class);
    Map<Token, Collection<DirectSpeech>> directSpeechCoveringMap = JCasUtil.indexCovering(aJCas, Token.class,
            DirectSpeech.class);

    Map<Token, Collection<SemanticPredicate>> predIdx = JCasUtil.indexCovered(aJCas, Token.class,
            SemanticPredicate.class);

    Map<SemanticPredicate, Collection<Token>> pred2TokenIdx = JCasUtil.indexCovering(aJCas,
            SemanticPredicate.class, Token.class);

    Map<SemanticArgument, Collection<Token>> argIdx = JCasUtil.indexCovered(aJCas, SemanticArgument.class,
            Token.class);

    //Coreference
    Map<Token, Collection<CoreferenceLink>> corefLinksCoveringMap = JCasUtil.indexCovering(aJCas, Token.class,
            CoreferenceLink.class);
    HashMap<CoreferenceLink, CoreferenceChain> linkToChainMap = new HashMap<>();
    HashMap<CoreferenceChain, Integer> corefChainToIntMap = new HashMap<>();

    int corefChainId = 0;
    for (CoreferenceChain chain : JCasUtil.select(aJCas, CoreferenceChain.class)) {

        CoreferenceLink link = chain.getFirst();
        int count = 0;
        while (link != null) {
            linkToChainMap.put(link, chain);
            link = link.getNext();/*  www.j a va  2 s .  com*/
            count++;
        }
        if (count > 0) {
            corefChainToIntMap.put(chain, corefChainId);
            corefChainId++;
        }
    }

    HashMap<Token, Row> ctokens = new LinkedHashMap<Token, Row>();

    Collection<Paragraph> paragraphs = select(aJCas, Paragraph.class);
    Collection<Sentence> sentences = select(aJCas, Sentence.class);
    TreeSet<Integer> sentenceEnds = new TreeSet<>();

    for (Sentence sentence : sentences) {
        sentenceEnds.add(sentence.getEnd());
    }

    for (Paragraph paragraph : paragraphs) {
        sentenceEnds.add(paragraph.getEnd());
    }

    for (Paragraph para : select(aJCas, Paragraph.class)) {

        for (Sentence sentence : selectCovered(Sentence.class, para)) {

            // Tokens
            List<Token> tokens = selectCovered(Token.class, sentence);

            // Check if we should try to include the morphology in output
            List<Morpheme> morphologies = selectCovered(Morpheme.class, sentence);
            boolean useMorphology = tokens.size() == morphologies.size();

            // Check if we should try to include the morphology in output
            List<Hyphenation> hyphenations = selectCovered(Hyphenation.class, sentence);
            boolean useHyphenation = tokens.size() == hyphenations.size();

            //Parsing information
            String[] parseFragments = null;
            List<ROOT> root = selectCovered(ROOT.class, sentence);
            if (root.size() == 1) {
                PennTreeNode rootNode = PennTreeUtils.convertPennTree(root.get(0));
                if ("ROOT".equals(rootNode.getLabel())) {
                    rootNode.setLabel("TOP");
                }
                parseFragments = toPrettyPennTree(rootNode);
            }
            boolean useParseFragements = (parseFragments != null && parseFragments.length == tokens.size());

            List<SemanticPredicate> preds = selectCovered(SemanticPredicate.class, sentence);

            for (int i = 0; i < tokens.size(); i++) {
                Row row = new Row();

                row.paragraphId = paragraphId;
                row.sentenceId = sentenceId;
                row.tokenId = tokenId;
                row.token = tokens.get(i);
                row.args = new SemanticArgument[preds.size()];

                if (useParseFragements) {
                    row.parseFragment = parseFragments[i];
                }

                if (useMorphology) {
                    row.morphology = morphologies.get(i);
                }

                if (useHyphenation) {
                    row.hyphenation = hyphenations.get(i);
                }

                // Section ID
                Collection<Section> section = sectionCoveringMap.get(row.token);
                if (section.size() > 0)
                    row.sectionId = section.toArray(new Section[0])[0].getValue();

                // Named entities
                Collection<NamedEntity> ne = neCoveringMap.get(row.token);
                if (ne.size() > 0)
                    row.ne = ne.toArray(new NamedEntity[0])[0];

                // Chunk
                Collection<Chunk> chunks = chunksCoveringMap.get(row.token);
                if (chunks.size() > 0)
                    row.chunk = chunks.toArray(new Chunk[0])[0];

                //Quote annotation
                Collection<DirectSpeech> ds = directSpeechCoveringMap.get(row.token);
                if (ds.size() > 0)
                    row.directSpeech = ds.toArray(new DirectSpeech[0])[0];

                //Coref
                Collection<CoreferenceLink> corefLinks = corefLinksCoveringMap.get(row.token);
                row.corefChains = UNUSED;
                if (corefLinks.size() > 0) {

                    String[] chainIds = new String[corefLinks.size()];
                    //                  StringBuilder chainIdsStr = new StringBuilder();

                    int k = 0;
                    for (CoreferenceLink link : corefLinks) {
                        CoreferenceChain chain = linkToChainMap.get(link);
                        int chainId = corefChainToIntMap.get(chain);

                        //chainIds[k++] = chainId;

                        String BIOMarker = "I";
                        if (link.getCoveredText().substring(0, row.token.getCoveredText().length())
                                .equals(row.token.getCoveredText())) {
                            BIOMarker = "B";
                        }
                        chainIds[k++] = BIOMarker + "-" + chainId;
                    }

                    //Sort without the BIO marker
                    Arrays.sort(chainIds, new Comparator<String>() {
                        public int compare(String idx1, String idx2) {
                            Integer id1 = new Integer(idx1.substring(2));
                            Integer id2 = new Integer(idx2.substring(2));

                            return Integer.compare(id1, id2);
                        }
                    });

                    StringBuilder chainIdsStr = new StringBuilder();
                    for (String chainId : chainIds) {
                        chainIdsStr.append(chainId + ",");
                    }

                    row.corefChains = chainIdsStr.substring(0, chainIdsStr.length() - 1);
                }

                //Predicate
                Collection<SemanticPredicate> predsForToken = predIdx.get(row.token);
                if (predsForToken != null && !predsForToken.isEmpty()) {
                    row.pred = predsForToken.iterator().next();
                }

                ctokens.put(row.token, row);
                tokenId++;
            }

            // Dependencies
            for (Dependency rel : selectCovered(Dependency.class, sentence)) {
                ctokens.get(rel.getDependent()).deprel = rel;
            }

            // Semantic arguments
            for (int p = 0; p < preds.size(); p++) {
                FSArray args = preds.get(p).getArguments();

                //Set the column position info
                Collection<Token> tokensOfPredicate = pred2TokenIdx.get(preds.get(p));
                for (Token t : tokensOfPredicate) {
                    Row row = ctokens.get(t);
                    row.semanticArgIndex = p;
                }

                //Set the arguments information
                for (SemanticArgument arg : select(args, SemanticArgument.class)) {
                    for (Token t : argIdx.get(arg)) {
                        Row row = ctokens.get(t);
                        row.args[p] = arg;
                    }
                }
            }

            sentenceId++;
        }
        paragraphId++;
    }

    // Write to output file
    int maxPredArguments = 0;
    for (Row row : ctokens.values()) {
        maxPredArguments = Math.max(maxPredArguments, row.args.length);
    }

    aOut.printf("%s\n", StringUtils.join(getHeader(maxPredArguments), "\t").trim());

    for (Row row : ctokens.values()) {
        String[] output = getData(ctokens, maxPredArguments, row);
        aOut.printf("%s\n", StringUtils.join(output, "\t").trim());
    }

}

From source file:jurbano.melodyshape.ui.ConsoleUIObserver.java

/**
 * Prints the usage message to stderr./* www.  j ava 2 s . co  m*/
 * 
 * @param options
 *            the command line options.
 */
protected void printUsage(Options options) {
    HelpFormatter formatter = new HelpFormatter();
    formatter.setOptionComparator(new Comparator<Option>() {
        public int compare(Option o1, Option o2) {
            List<String> options = Arrays.asList("q", "c", "a", "k", "l", "t", "v", "vv", "gui", "h");

            return Integer.compare(options.indexOf(o1.getOpt()), options.indexOf(o2.getOpt()));
        }
    });
    formatter.printHelp(new PrintWriter(System.err, true), Integer.MAX_VALUE,
            "melodyshape-" + MelodyShape.VERSION, null, options, 0, 2, "\n" + MelodyShape.COPYRIGHT_NOTICE,
            true);
}

From source file:com.opendoorlogistics.core.scripts.formulae.FmLookupNearest.java

@Override
public Object execute(FunctionParameters parameters) {
    TableParameters tp = (TableParameters) parameters;
    ODLTableReadOnly table = (ODLTableReadOnly) tp.getTableById(refs.datastoreIndx, refs.tableId);

    if (type == LCType.LL) {
        return executeLL(parameters, table);
    }/*from  www.j  a va2 s  .  com*/

    CachedProcessedGeom searchObject = getSearchGeom(parameters);
    if (searchObject == null || searchObject.geometry == null) {
        return Functions.EXECUTION_ERROR;
    }

    class RowElement implements Comparable<RowElement> {
        int row;
        CachedProcessedGeom geom;
        double minDistance;

        @Override
        public int compareTo(RowElement o) {
            int ret = Double.compare(minDistance, o.minDistance);
            if (ret == 0) {
                ret = Integer.compare(row, o.row);
            }
            return ret;
        }
    }

    // Get all geometries, transformed into the coord system and with bounding circles.
    // Place them in a binary heap, sorted by their minimum possible distance according to bounding circle
    int nr = table.getRowCount();
    BinaryHeap sortedHeap = new BinaryHeap();
    for (int row = 0; row < nr; row++) {
        CachedProcessedGeom otherGeom = null;
        switch (type) {
        case GL:
            Pair<LatLong, Boolean> result = getLatLongFromRow(table, row);
            if (result.getSecond() == false) {
                // critical error
                return Functions.EXECUTION_ERROR;
            } else if (result.getFirst() != null) {

                LatLong ll = result.getFirst();

                // put into our comparison object and convert
                otherGeom = new CachedProcessedGeom(ll, transform);
            }
            break;

        case GG:
        case LG: {
            Object val = table.getValueAt(row, refs.columnIndices[0]);
            if (val != null) {

                ODLGeomImpl odlGeom = (ODLGeomImpl) ColumnValueProcessor.convertToMe(ODLColumnType.GEOM, val);
                if (odlGeom == null) {
                    // critical error
                    return Functions.EXECUTION_ERROR;
                }

                otherGeom = toCoordSystem(odlGeom);
                if (otherGeom == null || otherGeom.geometry == null) {
                    // critical error
                    return Functions.EXECUTION_ERROR;
                }
            }
        }
        default:
            break;
        }

        if (otherGeom != null) {
            RowElement rowElement = new RowElement();
            rowElement.row = row;
            rowElement.minDistance = searchObject.boundingCircle.minimumSeparation(otherGeom.boundingCircle);
            rowElement.geom = otherGeom;
            sortedHeap.add(rowElement);
        }
    }

    // loop over the table
    RowElement closest = null;
    double closestDistance = Double.MAX_VALUE;
    while (sortedHeap.size() > 0) {
        RowElement row = (RowElement) sortedHeap.pop();
        if (row.minDistance > closestDistance) {
            // We can stop searching now as the minimum possible distance is greater than our closest
            break;
        }

        // Explicitly get the distance
        double distance = searchObject.geometry.distance(row.geom.geometry);
        if (distance < closestDistance) {
            closestDistance = distance;
            closest = row;
        }
    }

    if (closest != null) {
        return getReturnObject(table, closest.row);
    }

    return null;
}

From source file:bwem.map.MapImpl.java

public TilePosition breadthFirstSearch(TilePosition start, Pred findCond, Pred visitCond, boolean connect8) {
    if (findCond.isTrue(getData().getTile(start), start, this)) {
        return start;
    }//  w  w  w .j ava2  s .  co m

    final Set<TilePosition> visited = new TreeSet<>((a, b) -> {
        int result = Integer.compare(a.getX(), b.getX());
        if (result != 0) {
            return result;
        }
        return Integer.compare(a.getY(), b.getY());
    });
    Queue<TilePosition> toVisit = new ArrayDeque<>();

    toVisit.add(start);
    visited.add(start);

    TilePosition[] dir8 = { new TilePosition(-1, -1), new TilePosition(0, -1), new TilePosition(1, -1),
            new TilePosition(-1, 0), new TilePosition(1, 0), new TilePosition(-1, 1), new TilePosition(0, 1),
            new TilePosition(1, 1) };
    TilePosition[] dir4 = { new TilePosition(0, -1), new TilePosition(-1, 0), new TilePosition(+1, 0),
            new TilePosition(0, +1) };
    TilePosition[] directions = connect8 ? dir8 : dir4;

    while (!toVisit.isEmpty()) {
        TilePosition current = toVisit.remove();
        for (TilePosition delta : directions) {
            TilePosition next = current.add(delta);
            if (getData().getMapData().isValid(next)) {
                Tile nextTile = getData().getTile(next, CheckMode.NO_CHECK);
                if (findCond.isTrue(nextTile, next, this)) {
                    return next;
                }
                if (visitCond.isTrue(nextTile, next, this) && !visited.contains(next)) {
                    toVisit.add(next);
                    visited.add(next);
                }
            }
        }
    }

    //TODO: Are we supposed to return start or not?
    //        bwem_assert(false);
    throw new IllegalStateException();
    //        return start;
}

From source file:com.adobe.acs.commons.mcp.impl.processes.asset.UrlAssetImport.java

private int compareName(FileOrRendition a, FileOrRendition b, String fileName) {
    int aDist = StringUtils.getLevenshteinDistance(a.getName().toLowerCase(), fileName);
    int bDist = StringUtils.getLevenshteinDistance(b.getName().toLowerCase(), fileName);
    return Integer.compare(aDist, bDist);
}