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:fastcall.FArrayUtils.java

/**
 * Return an index of an array by ascending order of value
 * @param array/*from  w w  w.ja  v  a  2  s  .  co m*/
 * @return 
 */
public static int[] getIndexByAscendingValue(int[] array) {
    int[] inputArray = new int[array.length];
    System.arraycopy(array, 0, inputArray, 0, array.length);
    Integer[] idx = new Integer[inputArray.length];
    for (int i = 0; i < idx.length; i++)
        idx[i] = i;
    Arrays.sort(idx, new Comparator<Integer>() {
        public int compare(Integer i1, Integer i2) {
            return Integer.compare(inputArray[i1], inputArray[i2]);
        }
    });
    int[] index = new int[idx.length];
    for (int i = 0; i < index.length; i++)
        index[i] = idx[i];

    return index;
}

From source file:org.languagetool.rules.RuleMatch.java

/** Compare by start position. */
@Override/*  w  ww.j  ava  2  s.  c  o m*/
public int compareTo(final RuleMatch other) {
    Objects.requireNonNull(other);
    return Integer.compare(getFromPos(), other.getFromPos());
}

From source file:org.javersion.path.PropertyPath.java

@Override
public int compareTo(PropertyPath other) {
    List<SubPath> myPath = getFullPath();
    List<SubPath> otherPath = other.getFullPath();
    int len = Math.min(myPath.size(), otherPath.size());
    int cmp = 0;//from www.j  a  v a  2 s .co m
    for (int i = 0; i < len && cmp == 0; i++) {
        cmp = myPath.get(i).getNodeId().compareTo(otherPath.get(i).getNodeId());
    }
    return cmp == 0 ? Integer.compare(myPath.size(), otherPath.size()) : cmp;
}

From source file:com.jeans.iservlet.action.asset.AssetAction.java

/**
 * ?/*  w ww  .  jav a2 s  .com*/
 * 
 * @return
 * @throws Exception
 */
@Action(value = "load-assets", results = { @Result(type = "json", params = { "root", "data" }) })
public String loadAssets() throws Exception {
    long[] total = new long[1];
    List<Asset> assets = assetService.loadAssets(getCurrentCompany(), type, page, rows, total);
    List<AssetItem> assetItemsList = new ArrayList<AssetItem>();
    for (Asset asset : assets) {
        if (asset instanceof Hardware) {
            assetItemsList.add(HardwareItem.createInstance((Hardware) asset));
        } else if (asset instanceof Software) {
            assetItemsList.add(SoftwareItem.createInstance((Software) asset));
        }
    }
    data = new DataGrid<AssetItem>(total[0], assetItemsList);
    if (null != sort && data.getRows().size() > 0) {
        Collections.sort(data.getRows(), new Comparator<AssetItem>() {

            @Override
            public int compare(AssetItem o1, AssetItem o2) {
                int ret = 0;
                boolean asc = "asc".equals(order);
                boolean isHardware = o1 instanceof HardwareItem;
                switch (sort) {
                case "code":
                    ret = compString(((HardwareItem) o1).getCode(), ((HardwareItem) o2).getCode(), asc);
                    break;
                case "financialCode":
                    ret = compString(((HardwareItem) o1).getFinancialCode(),
                            ((HardwareItem) o2).getFinancialCode(), asc);
                    break;
                case "name":
                    if (isHardware) {
                        ret = compString(((HardwareItem) o1).getName(), ((HardwareItem) o2).getName(), asc);
                    } else {
                        ret = compString(((SoftwareItem) o1).getName(), ((SoftwareItem) o2).getName(), asc);
                    }
                    break;
                case "vendor":
                    if (isHardware) {
                        ret = compString(((HardwareItem) o1).getVendor(), ((HardwareItem) o2).getVendor(), asc);
                    } else {
                        ret = compString(((SoftwareItem) o1).getVendor(), ((SoftwareItem) o2).getVendor(), asc);
                    }
                    break;
                case "modelOrVersion":
                    if (isHardware) {
                        ret = compString(((HardwareItem) o1).getModelOrVersion(), ((HardwareItem) o2).getName(),
                                asc);
                    } else {
                        ret = compString(((SoftwareItem) o1).getModelOrVersion(),
                                ((SoftwareItem) o2).getModelOrVersion(), asc);
                    }
                    break;
                case "sn":
                    ret = compString(((HardwareItem) o1).getSn(), ((HardwareItem) o2).getSn(), asc);
                    break;
                case "purchaseTime":
                    Date t1 = isHardware ? ((HardwareItem) o1).getPurchaseTime()
                            : ((SoftwareItem) o1).getPurchaseTime();
                    Date t2 = isHardware ? ((HardwareItem) o2).getPurchaseTime()
                            : ((SoftwareItem) o2).getPurchaseTime();
                    if (null == t1) {
                        if (null == t2) {
                            ret = 0;
                        } else {
                            ret = asc ? -1 : 1;
                        }
                    } else {
                        if (null == t2) {
                            ret = asc ? 1 : -1;
                        } else {
                            ret = asc ? t1.compareTo(t2) : t2.compareTo(t1);
                        }
                    }
                    break;
                case "quantity":
                    if (isHardware) {
                        ret = asc
                                ? Integer.compare(((HardwareItem) o1).getQuantity(),
                                        ((HardwareItem) o2).getQuantity())
                                : Integer.compare(((HardwareItem) o2).getQuantity(),
                                        ((HardwareItem) o1).getQuantity());
                    } else {
                        ret = asc
                                ? Integer.compare(((SoftwareItem) o1).getQuantity(),
                                        ((SoftwareItem) o2).getQuantity())
                                : Integer.compare(((SoftwareItem) o2).getQuantity(),
                                        ((SoftwareItem) o1).getQuantity());
                    }
                    break;
                case "cost":
                    BigDecimal d1 = isHardware ? ((HardwareItem) o1).getCost() : ((SoftwareItem) o1).getCost();
                    BigDecimal d2 = isHardware ? ((HardwareItem) o2).getCost() : ((SoftwareItem) o2).getCost();
                    if (null == d1) {
                        d1 = new BigDecimal(0.0);
                    }
                    if (null == d2) {
                        d2 = new BigDecimal(0.0);
                    }
                    ret = asc ? d1.compareTo(d2) : d2.compareTo(d1);
                    break;
                case "state":
                    if (isHardware) {
                        ret = compString(((HardwareItem) o1).getState(), ((HardwareItem) o2).getState(), asc);
                    } else {
                        ret = compString(((SoftwareItem) o1).getState(), ((SoftwareItem) o2).getState(), asc);
                    }
                    break;
                case "warranty":
                    ret = compString(((HardwareItem) o1).getWarranty(), ((HardwareItem) o2).getWarranty(), asc);
                    break;
                case "location":
                    ret = compString(((HardwareItem) o1).getLocation(), ((HardwareItem) o2).getLocation(), asc);
                    break;
                case "ip":
                    ret = compString(((HardwareItem) o1).getIp(), ((HardwareItem) o2).getIp(), asc);
                    break;
                case "importance":
                    ret = compString(((HardwareItem) o1).getImportance(), ((HardwareItem) o2).getImportance(),
                            asc);
                    break;
                case "owner":
                    ret = compString(((HardwareItem) o1).getOwner(), ((HardwareItem) o2).getOwner(), asc);
                    break;
                case "softwareType":
                    ret = compString(((SoftwareItem) o1).getSoftwareType(),
                            ((SoftwareItem) o2).getSoftwareType(), asc);
                    break;
                case "license":
                    ret = compString(((SoftwareItem) o1).getLicense(), ((SoftwareItem) o2).getLicense(), asc);
                    break;
                case "expiredTime":
                    Date e1 = ((SoftwareItem) o1).getPurchaseTime();
                    Date e2 = ((SoftwareItem) o2).getPurchaseTime();
                    if (null == e1) {
                        if (null == e2) {
                            ret = 0;
                        } else {
                            ret = asc ? -1 : 1;
                        }
                    } else {
                        if (null == e2) {
                            ret = asc ? 1 : -1;
                        } else {
                            ret = asc ? e1.compareTo(e2) : e2.compareTo(e1);
                        }
                    }
                }
                return ret;
            }

            private int compString(String s1, String s2, boolean asc) {
                if (null == s1) {
                    if (null == s2) {
                        return 0;
                    } else {
                        return asc ? -1 : 1;
                    }
                } else {
                    if (null == s2) {
                        return asc ? 1 : -1;
                    } else {
                        return asc ? Collator.getInstance(java.util.Locale.CHINA).compare(s1, s2)
                                : Collator.getInstance(java.util.Locale.CHINA).compare(s2, s1);
                    }
                }
            }

        });
    }
    return SUCCESS;
}

From source file:uk.co.jassoft.markets.api.SentimentController.java

@PreAuthorize("permitAll")
@RequestMapping(value = "{direction}/period/{period}/limit/{limit}", method = RequestMethod.GET)
public @ResponseBody List<CompanySentiment> getChartToday(final HttpServletResponse response,
        @PathVariable String direction, @PathVariable PeriodType period, @PathVariable int limit)
        throws UnknownHostException {

    List<StorySentiment> storySentiments = storySentimentRepository
            .findByStoryDateGreaterThan(DateUtils.truncate(new Date(), Calendar.DATE));

    List<CompanySentiment> todayCompanySentiments = storySentiments.stream()
            .map(storySentiment -> new ImmutablePair<>(storySentiment.getCompany(),
                    storySentiment.getEntitySentiment().stream()
                            .collect(Collectors.summingInt(value -> value.getSentiment()))))
            .collect(Collectors.groupingBy(pair -> pair.getKey(),
                    Collectors.summingInt(value -> value.getValue())))
            .entrySet().stream().map(stringIntegerEntry -> {
                Company company = companyRepository.findOne(stringIntegerEntry.getKey());
                return new CompanySentiment(stringIntegerEntry.getKey(), company.getName(),
                        stringIntegerEntry.getValue());
            }).sorted((o1, o2) -> {//from   ww  w.  j av  a2s.co m
                switch (direction) {
                case "highest":
                    return Integer.compare(o2.getSentiment(), o1.getSentiment());

                case "lowest":
                default:
                    return Integer.compare(o1.getSentiment(), o2.getSentiment());
                }
            }).limit(limit).collect(Collectors.toList());

    response.setHeader("Cache-Control", "max-age=" + CacheTimeout.FIFTEEN_MINUTES);
    return todayCompanySentiments;
}

From source file:edu.ucla.cs.scai.canali.core.index.utils.DBpediaOntology201510Utils.java

public HashSet<String> createClassParentsFile() throws Exception {
    System.out.println("Saving class parents");
    HashSet<String> classes = new HashSet<>();
    try (PrintWriter out = new PrintWriter(new FileOutputStream(destinationPath + "class_parents", false),
            true)) {/*from   w  w  w .  j a v a  2s  .  c  om*/
        StmtIterator stmts = dbpedia.listStatements(null, RDFS.subClassOf, (RDFNode) null);
        while (stmts.hasNext()) {
            Statement stmt = stmts.next();
            out.println(stmt.getSubject() + "\t" + stmt.getObject());
            classes.add(stmt.getSubject().toString());
        }
        //now process Yago classes
        //first find the frequency of each class
        HashMap<String, Integer> classCount = new HashMap<>();
        try (BufferedReader in = new BufferedReader(new FileReader(downloadedFilesPath + "yago_types.nt"))) {
            String l = in.readLine();
            String regex = "<(.*)> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <(.*)>";
            Pattern p = Pattern.compile(regex);
            while (l != null) {
                Matcher m = p.matcher(l);
                if (m.find()) {
                    String cUri = m.group(2);
                    Integer c = classCount.get(cUri);
                    if (c == null) {
                        classCount.put(cUri, 1);
                    } else {
                        classCount.put(cUri, c + 1);
                    }
                }
                l = in.readLine();
            }
            in.close();
        }
        ArrayList<Map.Entry<String, Integer>> a = new ArrayList<>(classCount.entrySet());
        Collections.sort(a, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return Integer.compare(o2.getValue(), o1.getValue());
            }
        });
        double percentage = 1; //100%
        //add only the most frequent classes or those explicity listed above
        int threshold = (int) Math.ceil(percentage * a.size());
        for (int i = 0; i < threshold; i++) {
            classes.add(a.get(i).getKey());
        }
        for (String s : selectedYagoClasses) {
            classes.add(s);
        }
        try (BufferedReader in = new BufferedReader(new FileReader(downloadedFilesPath + "yago_taxonomy.nt"))) {
            String l = in.readLine();
            String regex = "(\\s*)<(.*)> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <(.*)>";
            Pattern p = Pattern.compile(regex);
            while (l != null) {
                Matcher m = p.matcher(l);
                if (m.find()) {
                    String aUri = m.group(2);
                    String bUri = m.group(3);
                    if (classes.contains(aUri) && classes.contains(bUri)) {
                        out.println(aUri + "\t" + bUri);
                    }
                }
                l = in.readLine();
            }
            in.close();
        }
    }
    return classes;
}

From source file:com.wrmsr.wava.TestWhatever.java

private static void showBasics(Name fname, BasicSet basics, boolean drawDoms) throws Exception {
    BasicDominatorInfo dt = BasicDominatorInfo.build(basics);
    BasicLoopInfo li = BasicLoopInfo.build(basics, dt);

    Function<Name, String> nameMangler = n -> n.get().replace('$', '_');
    StringBuilder sb = new StringBuilder();
    sb.append("digraph G {\n");
    sb.append("labelloc=\"t\";");
    sb.append(String.format("label=\"%s (%d)\";", fname.get(), basics.size()));
    List<Name> order = basics.basics().stream()
            .sorted((l, r) -> Integer.compare(l.getIndex().getAsInt(), r.getIndex().getAsInt()))
            .map(Basic::getName).collect(toImmutableList());
    for (Name name : order) {
        Basic basic = basics.get(name);//from   w  w  w .  jav a2s.c om
        Name idom = dt.getImmediateDominator(basic.getName());
        Set<Name> domFront = dt.getDominanceFrontiers().get(basic.getName());
        boolean isLoop = li.isLoop(basic.getName());
        boolean isIf = !isLoop && basic.getAllTargets().size() == 2; // FIXME WRONG 1035
        boolean isSingle = basics.getInputs(basic).size() == 1 && basic.getAllTargets().size() == 1;
        String nodeStyle = isLoop ? "fillcolor=blue,style=filled"
                : isIf ? "fillcolor=green,style=filled" : isSingle ? "fillcolor=orange,style=filled" : "";
        int totalSize = basic.getBody().stream().mapToInt(Analyses::getChildCount).sum();
        sb.append(String.format("%s [label=\"%s: %d, %d, %d\",%s];\n", nameMangler.apply(basic.getName()),
                basic.getName().get(), basic.getIndex().getAsInt(), basic.getBody().size(), totalSize,
                nodeStyle));
        if (drawDoms) {
            if (idom != null) {
                sb.append(String.format("%s -> %s [color=red];\n", nameMangler.apply(idom),
                        nameMangler.apply(basic.getName())));
            }
            domFront.forEach(df -> sb.append(String.format("%s -> %s [color=red,style=dotted];\n",
                    nameMangler.apply(basic.getName()), nameMangler.apply(df))));
        }
        Name loopParent = li.getLoopParent(name);
        if (loopParent != null) {
            sb.append(String.format("%s -> %s [color=blue,style=dotted];\n", nameMangler.apply(loopParent),
                    nameMangler.apply(basic.getName())));
        }
        basic.getAllTargets().forEach(output -> {
            String edgeStyle = li.getBackEdges().containsEntry(output, basic.getName()) ? "fillcolor=blue" : "";
            sb.append(String.format("%s -> %s [%s];\n", nameMangler.apply(basic.getName()),
                    nameMangler.apply(output), edgeStyle));
        });
    }
    Basics.TERMINAL_NAMES
            .forEach(n -> sb.append(String.format("%s [label=\"%s\"];\n", nameMangler.apply(n), n.get())));
    sb.append("}\n");
    showGraph(sb.toString());
}

From source file:de.tudarmstadt.ukp.dkpro.core.frequency.phrasedetection.FrequencyCounter.java

/**
 * Write counter with counts from a bag to an output stream.
 *
 * @param os      an {@link OutputStream}
 * @param counter a {@link Bag} of string counter
 *///w  ww  .  j a  va2 s .  c  o  m
private void writeNgrams(OutputStream os, Bag<String> counter) {
    /* create token stream */
    Stream<String> stream = counter.uniqueSet().stream().filter(token -> counter.getCount(token) >= minCount);

    /* sort output */
    if (sortByAlphabet) {
        stream = stream.sorted(String::compareTo);
    } else if (sortByCount) {
        stream = stream.sorted((o1, o2) -> -Integer.compare(counter.getCount(o1), counter.getCount(o2)));
    }

    /* write tokens with counts */
    stream.forEach(token -> {
        try {
            os.write((token + COLUMN_SEPARATOR + counter.getCount(token) + "\n").getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });
}

From source file:se.uu.it.cs.recsys.service.resource.impl.RecommendationGenerator.java

Set<Integer> filterOnPlanYear(Set<Integer> courseId) {
    if (courseId.isEmpty()) {
        return Collections.emptySet();
    }//from ww  w . j  av  a  2 s  .  c  o m

    Set<se.uu.it.cs.recsys.persistence.entity.Course> filteredCourse = this.courseRepository
            .findByAutoGenIds(courseId).stream()
            .filter(ConstraintSolverPreferenceBuilder
                    .inPlanYearPredicate(this.constraintPref.getIndexedScheduleInfo()))
            .sorted((se.uu.it.cs.recsys.persistence.entity.Course one,
                    se.uu.it.cs.recsys.persistence.entity.Course two) -> Integer.compare(one.getAutoGenId(),
                            two.getAutoGenId()))
            .collect(Collectors.toSet());

    filteredCourse.forEach(course -> LOGGER.debug("Filtered course: {}", course));

    return filteredCourse.stream().map(course -> course.getAutoGenId()).collect(Collectors.toSet());
}

From source file:tds.student.performance.services.impl.ItemBankServiceImpl.java

@Cacheable(CacheType.MediumTerm)
public AccList getTestAccommodations(String testKey) throws ReturnStatusException {
    AccList accList = new AccList();
    try (SQLConnection connection = getSQLConnection()) {

        // TODO: look into this "stored proc" - the optimization attempt adds complexity
        Iterator<SingleDataResultSet> results = _commonDll.IB_GetTestAccommodations_SP(connection, testKey)
                .getResultSets();//from www.j  ava 2  s .co  m
        if (results.hasNext()) {
            SingleDataResultSet firstResultSet = results.next();
            ReturnStatusException.getInstanceIfAvailable(firstResultSet);
            Iterator<DbResultRecord> records = firstResultSet.getRecords();
            while (records.hasNext()) {
                DbResultRecord record = records.next();
                Data accData = AccListParseData.parseData(record);
                // HACK: Skip loading non-functional accommodations
                if (!accData.isFunctional())
                    continue;
                accList.add(accData);
            }
            if (results.hasNext()) {
                SingleDataResultSet secondResultSet = results.next();
                records = secondResultSet.getRecords();
                while (records.hasNext()) {
                    DbResultRecord record = records.next();
                    accList.getDependencies().add(AccListParseData.parseDependency(record));
                }
            }
        }
    } catch (SQLException e) {
        _logger.error(e.getMessage());
        throw new ReturnStatusException(e);
    }
    Collections.sort(accList.getData(), new Comparator<Data>() {
        @Override
        public int compare(Data acc1, Data acc2) {
            if (acc1.getSegmentPosition() != acc2.getSegmentPosition())
                return Integer.compare(acc1.getSegmentPosition(), acc2.getSegmentPosition());
            if (acc1.getToolTypeSortOrder() != acc2.getToolTypeSortOrder())
                return Integer.compare(acc1.getToolTypeSortOrder(), acc2.getToolTypeSortOrder());
            if (acc1.getToolValueSortOrder() != acc2.getToolValueSortOrder())
                return Integer.compare(acc1.getToolValueSortOrder(), acc2.getToolValueSortOrder());
            return 0;
        }
    });
    return accList;
}