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:com.vmware.photon.controller.apife.backends.TaskSqlBackend.java

private Task toApiRepresentation(TaskEntity taskEntity) {
    Task task = new Task();

    task.setId(taskEntity.getId());/*from www .  j  av  a2 s . c om*/
    task.setQueuedTime(taskEntity.getQueuedTime());
    task.setStartedTime(taskEntity.getStartedTime());
    task.setEndTime(taskEntity.getEndTime());
    task.setOperation(taskEntity.getOperation().toString());
    task.setState(taskEntity.getState().toString());

    Task.Entity entity = new Task.Entity();
    entity.setId(taskEntity.getEntityId());
    entity.setKind(taskEntity.getEntityKind());
    task.setEntity(entity);

    if (StringUtils.isNotBlank(taskEntity.getResourceProperties())) {
        try {
            Object resourceProperties = objectMapper.readValue(taskEntity.getResourceProperties(),
                    Object.class);
            task.setResourceProperties(resourceProperties);
        } catch (IOException e) {
            logger.error("Error deserializing taskEntity resourceProperties {}",
                    taskEntity.getResourceProperties(), e);
            throw new IllegalArgumentException(
                    String.format("Error deserializing taskEntity resourceProperties %s, error %s",
                            taskEntity.getResourceProperties(), e.getMessage()));
        }
    }

    List<Step> steps = new ArrayList<>();
    Collections.sort(taskEntity.getSteps(), new Comparator<StepEntity>() {
        @Override
        public int compare(StepEntity s1, StepEntity s2) {
            return Integer.compare(s1.getSequence(), s2.getSequence());
        }
    });
    for (StepEntity stepEntity : taskEntity.getSteps()) {
        steps.add(stepBackend.toApiRepresentation(stepEntity));
    }
    task.setSteps(steps);

    return task;
}

From source file:tds.student.sql.repository.ItemBankRepository.java

/**
 * This has been replaced by ItemBankService.getGrades.
 *
 * @deprecated use {@link #ItemBankService.getGrades()} instead.
 *///from w w  w  .  j  av  a  2 s  .c o m
public List<String> getGrades() throws ReturnStatusException {

    List<TestGrade> testGrades = new ArrayList<TestGrade>();

    try (SQLConnection connection = getSQLConnection()) {

        String testKey = null;
        SingleDataResultSet firstResultSet = _studentDll.IB_GetTestGrades_SP(connection,
                getTdsSettings().getClientName(), testKey, getTdsSettings().getSessionType());

        ReturnStatusException.getInstanceIfAvailable(firstResultSet);
        Iterator<DbResultRecord> records = firstResultSet.getRecords();
        while (records.hasNext()) {
            DbResultRecord record = records.next();
            TestGrade testGrade = new TestGrade(record.<String>get("grade"));
            if (testGrades.contains(testGrade))
                continue;
            testGrades.add(testGrade);
        }
    } catch (SQLException e) {
        _logger.error(e.getMessage());
        throw new ReturnStatusException(e);
    }

    Collections.<TestGrade>sort(testGrades, new Comparator<TestGrade>() {
        @Override
        public int compare(TestGrade o1, TestGrade o2) {
            int compare = Integer.compare(o1.getInteger(), o2.getInteger());
            if (compare == 0)
                return o1.getText().compareTo(o2.getText());
            return compare;
        }
    });
    return (List<String>) ((CollectionUtils.collect(testGrades, new Transformer() {
        public Object transform(Object each) {
            return ((TestGrade) each).getText();
        }
    }, new ArrayList<String>())));
}

From source file:net.dv8tion.jda.entities.impl.MessageImpl.java

@Override
public String getStrippedContent() {
    if (strippedContent == null) {
        String tmp = getContent();
        //all the formatting keys to keep track of
        String[] keys = new String[] { "*", "_", "`", "~~" };

        //find all tokens (formatting strings described above)
        TreeSet<FormatToken> tokens = new TreeSet<>((t1, t2) -> Integer.compare(t1.start, t2.start));
        for (String key : keys) {
            Matcher matcher = Pattern.compile(Pattern.quote(key)).matcher(tmp);
            while (matcher.find()) {
                tokens.add(new FormatToken(key, matcher.start()));
            }//from  w w  w. j av a 2  s .c o m
        }

        //iterate over all tokens, find all matching pairs, and add them to the list toRemove
        Stack<FormatToken> stack = new Stack<>();
        List<FormatToken> toRemove = new ArrayList<>();
        boolean inBlock = false;
        for (FormatToken token : tokens) {
            if (stack.empty() || !stack.peek().format.equals(token.format)
                    || stack.peek().start + token.format.length() == token.start) {
                //we are at opening tag
                if (!inBlock) {
                    //we are outside of block -> handle normally
                    if (token.format.equals("`")) {
                        //block start... invalidate all previous tags
                        stack.clear();
                        inBlock = true;
                    }
                    stack.push(token);
                } else if (token.format.equals("`")) {
                    //we are inside of a block -> handle only block tag
                    stack.push(token);
                }
            } else if (!stack.empty()) {
                //we found a matching close-tag
                toRemove.add(stack.pop());
                toRemove.add(token);
                if (token.format.equals("`") && stack.empty()) {
                    //close tag closed the block
                    inBlock = false;
                }
            }
        }

        //sort tags to remove by their start-index and iteratively build the remaining string
        Collections.sort(toRemove, (t1, t2) -> Integer.compare(t1.start, t2.start));
        StringBuilder out = new StringBuilder();
        int currIndex = 0;
        for (FormatToken formatToken : toRemove) {
            if (currIndex < formatToken.start) {
                out.append(tmp.substring(currIndex, formatToken.start));
            }
            currIndex = formatToken.start + formatToken.format.length();
        }
        if (currIndex < tmp.length()) {
            out.append(tmp.substring(currIndex));
        }
        //return the stripped text, escape all remaining formatting characters (did not have matching open/close before or were left/right of block
        strippedContent = out.toString().replace("*", "\\*").replace("_", "\\_").replace("~", "\\~");
    }
    return strippedContent;
}

From source file:org.mitre.mpf.wfm.data.entities.transients.Track.java

protected int compareDetections(SortedSet<Detection> a, SortedSet<Detection> b) {
    if (a == null && b == null) {
        return 0;
    } else if (a == null) {
        return 1;
    } else if (b == null) {
        return -1;
    } else {/*  www .  ja  v a  2s . com*/
        int comparisonResult = 0;
        comparisonResult = Integer.compare(a.size(), b.size());
        Iterator<Detection> firstIterator = a.iterator();
        Iterator<Detection> secondIterator = b.iterator();
        while ((comparisonResult == 0 && firstIterator.hasNext() && secondIterator.hasNext())) {
            Detection first = firstIterator.next();
            Detection second = secondIterator.next();
            if (first == null && second == null) {
                comparisonResult = 0;
            } else if (first == null) {
                comparisonResult = -1; // null < non-null
            } else if (second == null) {
                comparisonResult = 1;
            } else {
                comparisonResult = first.compareTo(second);
            }
        }
        return comparisonResult;
    }
}

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

public static Node worst(Map<Name, Basic> basics, Set<Name> loops) {
    checkState(basics.values().stream().allMatch(basic -> basic.getIndex().isPresent()));
    checkState(basics.values().stream().flatMap(basic -> optionalToStream(basic.getIndex()).boxed())
            .collect(toImmutableSet()).size() == basics.size());
    List<Basic> basicList = new ArrayList<>(basics.values());
    Collections.sort(basicList,/*from  w  w  w .  j av  a  2s.  c  o m*/
            (left, right) -> Integer.compare(left.getIndex().getAsInt(), right.getIndex().getAsInt()));
    checkState(!basicList.isEmpty());

    Node ret = new Nop();
    for (Basic basic : basicList) {
        Block body = new Block(ImmutableList.<Node>builder().add(ret).addAll(basic.getBody())
                .addAll(optionalToList(Basics.simplifyBreakTable(basic.getBreakTable()))).build());
        if (loops.contains(basic.getName())) {
            ret = new Loop(basic.getName(), body);
        } else {
            ret = new Label(basic.getName(), body);
        }
    }

    return ret;
}

From source file:com.ethercamp.harmony.service.BlockchainInfoService.java

@Scheduled(fixedRate = 2000)
private void doUpdateNetworkInfo() {
    final NetworkInfoDTO info = new NetworkInfoDTO(channelManager.getActivePeers().size(),
            NetworkInfoDTO.SyncStatusDTO.instanceOf(syncManager.getSyncStatus()), config.listenPort(), true);

    final HashMap<String, Integer> miners = new HashMap<>();
    lastBlocksForHashRate.stream().forEach(b -> {
        String minerAddress = Hex.toHexString(b.getCoinbase());
        int count = miners.containsKey(minerAddress) ? miners.get(minerAddress) : 0;
        miners.put(minerAddress, count + 1);
    });/* w ww  . j av  a2s. com*/

    final List<MinerDTO> minersList = miners.entrySet().stream()
            .map(entry -> new MinerDTO(entry.getKey(), entry.getValue()))
            .sorted((a, b) -> Integer.compare(b.getCount(), a.getCount())).limit(3).collect(toList());
    info.getMiners().addAll(minersList);

    networkInfo.set(info);

    clientMessageService.sendToTopic("/topic/networkInfo", info);
}

From source file:delfos.dataset.basic.rating.RatingsDatasetAdapter.java

public static <RatingType extends Rating> int hashCode(RatingsDataset<RatingType> ratingsDataset) {
    HashCodeBuilder hashCodeBuilder = new HashCodeBuilder(37, 11);

    List<Integer> usersSorted = ratingsDataset.allUsers().stream().collect(Collectors.toList());
    usersSorted.sort((i1, i2) -> Integer.compare(i1, i2));

    List<Integer> itemsSorted = ratingsDataset.allRatedItems().stream().collect(Collectors.toList());
    itemsSorted.sort((i1, i2) -> Integer.compare(i1, i2));

    for (int idUser : usersSorted) {
        hashCodeBuilder.append(idUser);//from ww  w . j  a  v a2s  .c  o  m
        try {
            Map<Integer, RatingType> userRatingsRated = ratingsDataset.getUserRatingsRated(idUser);

            List<Integer> thisUserItemsSorted = userRatingsRated.keySet().stream()
                    .sorted((i1, i2) -> Integer.compare(i1, i2)).collect(Collectors.toList());
            for (Integer idItem : thisUserItemsSorted) {
                RatingType rating = userRatingsRated.get(idItem);
                double ratingValue = rating.getRatingValue().doubleValue();
                hashCodeBuilder.append(idItem);
                hashCodeBuilder.append(ratingValue);
            }
        } catch (UserNotFound ex) {
            ERROR_CODES.USER_NOT_FOUND.exit(ex);
        }
    }

    return hashCodeBuilder.hashCode();
}

From source file:tds.student.sql.repositorysp.ItemBankRepository.java

public List<String> getGrades() throws ReturnStatusException {
    final String CMD_GET_TEST_GRADES = "BEGIN; SET NOCOUNT ON; exec IB_GetTestGrades ${clientName}, ${testKey}, ${sessiontype}; end;";

    List<TestGrade> testGrades = new ArrayList<TestGrade>();

    try (SQLConnection connection = getSQLConnection()) {
        // build parameters
        SqlParametersMaps parametersQuery = new SqlParametersMaps();

        parametersQuery.put("clientname", getTdsSettings().getClientName());
        parametersQuery.put("testKey", null);
        parametersQuery.put("sessiontype", getTdsSettings().getSessionType());

        SingleDataResultSet firstResultSet = executeStatement(connection, CMD_GET_TEST_GRADES, parametersQuery,
                false).getResultSets().next();

        ReturnStatusException.getInstanceIfAvailable(firstResultSet);
        Iterator<DbResultRecord> records = firstResultSet.getRecords();
        while (records.hasNext()) {
            DbResultRecord record = records.next();
            TestGrade testGrade = new TestGrade(record.<String>get("grade"));
            if (testGrades.contains(testGrade))
                continue;
            testGrades.add(testGrade);/*from  w ww .  j  a v  a2s. c  o m*/
        }
    } catch (SQLException e) {
        _logger.error(e.getMessage());
        throw new ReturnStatusException(e);
    }

    Collections.<TestGrade>sort(testGrades, new Comparator<TestGrade>() {
        @Override
        public int compare(TestGrade o1, TestGrade o2) {
            int compare = Integer.compare(o1.getInteger(), o2.getInteger());
            if (compare == 0)
                return o1.getText().compareTo(o2.getText());
            return compare;
        }
    });
    return (List<String>) ((CollectionUtils.collect(testGrades, new Transformer() {
        public Object transform(Object each) {
            return ((TestGrade) each).getText();
        }
    }, new ArrayList<String>())));
}

From source file:de.steilerdev.myVerein.server.model.Division.java

/**
 * This function is comparable to other divisions according to their distance to the root node.
 * @param o The division which is compared to the current division.
 * @return A negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. If o is null, 0 is returned.
 *///from  w w  w  .j a va2 s . c  o m
@Override
public int compareTo(Division o) {
    if (o != null) {
        try {
            List<Division> thisAncestors = this.getAncestors(), otherAncestors = o.getAncestors();

            if (thisAncestors == null || thisAncestors.isEmpty()) {
                return 1;
            } else if (otherAncestors == null || otherAncestors.isEmpty()) {
                return -1;
            } else {
                return Integer.compare(thisAncestors.size(), otherAncestors.size());
            }
        } catch (LazyLoadingException e) {
            logger.error("Unable to compare divisions {} {}: {}", o, this, e.getLocalizedMessage());
            return 0;
        }
    } else {
        logger.error("Comparing {} with null division", this);
        return 0;
    }
}

From source file:nu.yona.server.device.service.DeviceService.java

private DeviceAnonymizedDto getDefaultDeviceAnonymized(UserAnonymizedDto userAnonymized) {
    return userAnonymized.getDevicesAnonymized().stream()
            .sorted((d1, d2) -> Integer.compare(d1.getDeviceIndex(), d2.getDeviceIndex())).findFirst()
            .orElseThrow(() -> DeviceServiceException.noDevicesFound(userAnonymized.getId()));
}