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:org.apache.samza.system.hdfs.HdfsSystemAdmin.java

/**
 * Compare two multi-file style offset. A multi-file style offset consist of both
 * the file index as well as the offset within that file. And the format of it is:
 * "fileIndex:offsetWithinFile"/*from ww  w . j a v  a  2s .  c  o  m*/
 * For example, "2:0", "3:127"
 * Format of the offset within file is defined by the implementation of
 * {@link org.apache.samza.system.hdfs.reader.SingleFileHdfsReader} itself.
 *
 * @param offset1 First offset for comparison.
 * @param offset2 Second offset for comparison.
 * @return -1, if offset1 @lt offset2
 *          0, if offset1 == offset2
 *          1, if offset1 @gt offset2
 *          null, if not comparable
 */
@Override
public Integer offsetComparator(String offset1, String offset2) {
    if (StringUtils.isBlank(offset1) || StringUtils.isBlank(offset2)) {
        return null;
    }
    int fileIndex1 = MultiFileHdfsReader.getCurFileIndex(offset1);
    int fileIndex2 = MultiFileHdfsReader.getCurFileIndex(offset2);
    if (fileIndex1 == fileIndex2) {
        String offsetWithinFile1 = MultiFileHdfsReader.getCurSingleFileOffset(offset1);
        String offsetWithinFile2 = MultiFileHdfsReader.getCurSingleFileOffset(offset2);
        return HdfsReaderFactory.offsetComparator(readerType, offsetWithinFile1, offsetWithinFile2);
    }
    return Integer.compare(fileIndex1, fileIndex2);
}

From source file:org.haiku.haikudepotserver.pkg.PkgScreenshotServiceImpl.java

private void reorderPkgScreenshotsByHashSha256s(Pkg pkg, List<String> hashSha256s) {

    List<PkgScreenshot> screenshots = new ArrayList<>(pkg.getPkgScreenshots());

    screenshots.sort((o1, o2) -> {//from  w  w  w .  j a  v  a  2  s  .com
        int o1i = hashSha256s.indexOf(o1.getHashSha256());
        int o2i = hashSha256s.indexOf(o2.getHashSha256());

        if (-1 == o1i && -1 == o2i) {
            return o1.getCode().compareTo(o2.getCode());
        }

        if (-1 == o1i) {
            o1i = Integer.MAX_VALUE;
        }

        if (-1 == o2i) {
            o2i = Integer.MAX_VALUE;
        }

        return Integer.compare(o1i, o2i);
    });

    for (int i = 0; i < screenshots.size(); i++) {
        PkgScreenshot pkgScreenshot = screenshots.get(i);
        pkgScreenshot.setOrdering(i + 1);
    }
}

From source file:com.jsmartframework.web.manager.ContextControl.java

private List<String> sortCustomFilters() {
    // Sort the custom filter by the order specified
    List<String> customFilters = new ArrayList<String>(HANDLER.webFilters.keySet());
    Collections.sort(customFilters, new Comparator<String>() {

        @Override/*from ww w  .  j  a  v a  2s  .c om*/
        public int compare(String filterNameOne, String filterNameTwo) {
            WebFilter webFilterOne = HANDLER.webFilters.get(filterNameOne).getAnnotation(WebFilter.class);
            WebFilter webFilterTwo = HANDLER.webFilters.get(filterNameTwo).getAnnotation(WebFilter.class);
            return Integer.compare(webFilterOne.order(), webFilterTwo.order());
        }
    });
    return customFilters;
}

From source file:org.deidentifier.arx.DataHandle.java

/**
 * Returns a mapping from data types to the relative number of values that conform to the according type.
 *
 * @param column the column// w  w  w.j a  v a  2  s  .  c  o m
 * @param locale The locale to use
 * @param threshold Relative minimal number of values that must match to include a data type in the results
 * @return the matching data types
 */
public List<Pair<DataType<?>, Double>> getMatchingDataTypes(int column, Locale locale, double threshold) {

    checkRegistry();
    checkColumn(column);
    List<Pair<DataType<?>, Double>> result = new ArrayList<Pair<DataType<?>, Double>>();
    result.addAll(getMatchingDataTypes(column, Long.class, locale, threshold));
    result.addAll(getMatchingDataTypes(column, Date.class, locale, threshold));
    result.addAll(getMatchingDataTypes(column, Double.class, locale, threshold));
    result.add(new Pair<DataType<?>, Double>(DataType.STRING, 1.0d));

    // Sort order
    final Map<Class<?>, Integer> order = new HashMap<Class<?>, Integer>();
    order.put(Long.class, 0);
    order.put(Date.class, 1);
    order.put(Double.class, 2);
    order.put(String.class, 3);

    // Sort
    Collections.sort(result, new Comparator<Pair<DataType<?>, Double>>() {
        public int compare(Pair<DataType<?>, Double> o1, Pair<DataType<?>, Double> o2) {

            // Sort by matching quality
            int cmp = o1.getSecond().compareTo(o2.getSecond());
            if (cmp != 0)
                return -cmp;

            // Sort by order
            int order1 = order.get(o1.getFirst().getDescription().getWrappedClass());
            int order2 = order.get(o2.getFirst().getDescription().getWrappedClass());
            return Integer.compare(order1, order2);
        }
    });
    return result;
}

From source file:com.evolveum.midpoint.wf.impl.processors.primary.policy.ApprovalSchemaBuilder.java

private void sortFragments(List<Fragment> fragments) {
    fragments.forEach(f -> {//from w w w  . j  av  a 2 s  .  c om
        if (f.compositionStrategy != null && BooleanUtils.isTrue(f.compositionStrategy.isMergeable())
                && f.compositionStrategy.getOrder() == null) {
            throw new IllegalStateException("Mergeable composition strategy with no order: "
                    + f.compositionStrategy + " in " + f.policyRule);
        }
    });

    // relying on the fact that the sort algorithm is stable
    fragments.sort((f1, f2) -> {
        ApprovalCompositionStrategyType s1 = f1.compositionStrategy;
        ApprovalCompositionStrategyType s2 = f2.compositionStrategy;
        Integer o1 = s1 != null ? s1.getOrder() : null;
        Integer o2 = s2 != null ? s2.getOrder() : null;
        if (o1 == null || o2 == null) {
            return MiscUtil.compareNullLast(o1, o2);
        }
        int c = Integer.compare(o1, o2);
        if (c != 0) {
            return c;
        }
        // non-mergeable first
        boolean m1 = BooleanUtils.isTrue(s1.isMergeable());
        boolean m2 = BooleanUtils.isTrue(s2.isMergeable());
        if (m1 && !m2) {
            return 1;
        } else if (!m1 && m2) {
            return -1;
        } else {
            return 0;
        }
    });
}

From source file:bwem.map.MapImpl.java

public WalkPosition breadthFirstSearch(final WalkPosition start, final Pred findCond, final Pred visitCond,
        final boolean connect8) {
    if (findCond.isTrue(getData().getMiniTile(start), start, this)) {
        return start;
    }/*from w ww .  j  a  va2s  .  c  om*/

    final Set<WalkPosition> 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());
    });
    final Queue<WalkPosition> toVisit = new ArrayDeque<>();

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

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

    while (!toVisit.isEmpty()) {
        final WalkPosition current = toVisit.remove();
        for (final WalkPosition delta : directions) {
            final WalkPosition next = current.add(delta);
            if (getData().getMapData().isValid(next)) {
                final MiniTile miniTile = getData().getMiniTile(next, CheckMode.NO_CHECK);
                if (findCond.isTrue(miniTile, next, this)) {
                    return next;
                }
                if (visitCond.isTrue(miniTile, 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:edu.cmu.tetrad.search.TimeSeriesUtils.java

/**
 * Creates new time series dataset from the given one (fixed to deal with mixed datasets)
 *///w  w w  .  java2 s  . c o m
public static DataSet createLagData(DataSet data, int numLags) {
    List<Node> variables = data.getVariables();
    int dataSize = variables.size();
    int laggedRows = data.getNumRows() - numLags;
    IKnowledge knowledge = new Knowledge2();
    Node[][] laggedNodes = new Node[numLags + 1][dataSize];
    List<Node> newVariables = new ArrayList<>((numLags + 1) * dataSize + 1);

    for (int lag = 0; lag <= numLags; lag++) {
        for (int col = 0; col < dataSize; col++) {
            Node node = variables.get(col);
            String varName = node.getName();
            Node laggedNode;
            String name = varName;

            if (lag != 0) {
                name = name + ":" + lag;
            }

            if (node instanceof ContinuousVariable) {
                laggedNode = new ContinuousVariable(name);
            } else if (node instanceof DiscreteVariable) {
                DiscreteVariable var = (DiscreteVariable) node;
                laggedNode = new DiscreteVariable(var);
                laggedNode.setName(name);
            } else {
                throw new IllegalStateException("Node must be either continuous or discrete");
            }
            newVariables.add(laggedNode);
            laggedNode.setCenter(80 * col + 50, 80 * (numLags - lag) + 50);
            laggedNodes[lag][col] = laggedNode;
            //                knowledge.addToTier(numLags - lag, laggedNode.getName());
        }
    }

    //        System.out.println("Variable list before the sort = " + newVariables);
    Collections.sort(newVariables, new Comparator<Node>() {
        @Override
        public int compare(Node o1, Node o2) {
            String name1 = getNameNoLag(o1);
            String name2 = getNameNoLag(o2);

            //                System.out.println("name 1 = " + name1);
            //                System.out.println("name 2 = " + name2);

            String prefix1 = getPrefix(name1);
            String prefix2 = getPrefix(name2);

            //                System.out.println("prefix 1 = " + prefix1);
            //                System.out.println("prefix 2 = " + prefix2);

            int index1 = getIndex(name1);
            int index2 = getIndex(name2);

            //                System.out.println("index 1 = " + index1);
            //                System.out.println("index 2 = " + index2);

            if (getLag(o1.getName()) == getLag(o2.getName())) {
                if (prefix1.compareTo(prefix2) == 0) {
                    return Integer.compare(index1, index2);
                } else {
                    return prefix1.compareTo(prefix2);
                }

            } else {
                return getLag(o1.getName()) - getLag(o2.getName());
            }
        }
    });

    //        System.out.println("Variable list after the sort = " + newVariables);

    for (Node node : newVariables) {
        String varName = node.getName();
        String tmp;
        int lag;
        if (varName.indexOf(':') == -1) {
            lag = 0;
            //                laglist.add(lag);
        } else {
            tmp = varName.substring(varName.indexOf(':') + 1, varName.length());
            lag = Integer.parseInt(tmp);
            //                laglist.add(lag);
        }
        knowledge.addToTier(numLags - lag, node.getName());
    }

    DataSet laggedData = new ColtDataSet(laggedRows, newVariables);
    for (int lag = 0; lag <= numLags; lag++) {
        for (int col = 0; col < dataSize; col++) {
            for (int row = 0; row < laggedRows; row++) {
                Node laggedNode = laggedNodes[lag][col];
                if (laggedNode instanceof ContinuousVariable) {
                    double value = data.getDouble(row + numLags - lag, col);
                    laggedData.setDouble(row, col + lag * dataSize, value);
                } else {
                    int value = data.getInt(row + numLags - lag, col);
                    laggedData.setInt(row, col + lag * dataSize, value);
                }
            }
        }
    }

    knowledge.setDefaultToKnowledgeLayout(true);
    //        knowledge.setLagged(true);
    laggedData.setKnowledge(knowledge);
    //        laggedData.setName(data.getNode());
    return laggedData;
}

From source file:de.tudarmstadt.ukp.dkpro.discourse.pdtbparser.PDTBDiscourseAnnotator.java

private static void annotateParagraph(Paragraph paragraph, Element xmlParagraph, JCas jCas, boolean verbose) {
    Elements elements = xmlParagraph.getChildElements();
    if (elements.size() == 0) {
        System.err.println("No tokens found in paragraph" + xmlParagraph.toXML());
        return;//  w ww.j  ava2s  .c om
    }

    List<Token> tokens = JCasUtil.selectCovered(Token.class, paragraph);
    Elements xmlTokens = xmlParagraph.getChildElements("token");

    if (xmlTokens.size() != tokens.size()) {
        System.err.println(
                "Could not map PDTB parse output back to the current paragraph:\n" + paragraph.getCoveredText()
                        + "\nPDTB Parser returned the following:\n" + xmlParagraph.toXML());
        return;
    }

    List<DiscourseArgument> discourseArguments = new ArrayList<>();
    List<DiscourseConnective> discourseConnectives = new ArrayList<>();
    List<DiscourseAttribution> discourseAttributions = new ArrayList<>();

    // relation id and true=explicit, false=implicit
    Map<Integer, Boolean> discourseRelations = new HashMap<>();

    int elementsPosition = 0;
    int tokensPosition = 0;
    //        while (tokensPosition < tokens.size()) {
    if (verbose) {
        System.out.println(xmlParagraph.toXML());
    }

    while (elementsPosition < elements.size()) {
        Token token = null;
        if (tokensPosition < tokens.size()) {
            token = tokens.get(tokensPosition);
        }

        Token prevToken = null;
        if (tokensPosition > 0) {
            prevToken = tokens.get(tokensPosition - 1);
        }

        Element element = elements.get(elementsPosition);

        if (verbose) {
            System.out.println(element.toXML());
        }

        switch (element.getLocalName()) {
        case "token": {
            // we do nothing here
            tokensPosition++;
            break;
        }
        case "rel": {
            // we have some relation etc. - do the annotation here!
            Integer relationId = Integer.valueOf(element.getAttributeValue("id"));
            boolean isBegin = element.getAttributeValue("marker").equals("begin");

            // <rel type='exp' id='0' arg='1' marker='begin' />
            // or
            // <rel type='exp' id='0' connectiveType='Contrast' marker='begin' />

            // is connective?
            String connectiveType = element.getAttributeValue("connectiveType");
            if (connectiveType != null) {
                // are we opening a connective?
                if (isBegin) {
                    if (token == null) {
                        throw new IllegalStateException("Cannot begin discourse relation without token");
                    }

                    DiscourseConnective discourseConnective = new DiscourseConnective(jCas);
                    discourseConnective.setConnectiveType(connectiveType);
                    discourseConnective.setParentRelationId(relationId);

                    // set begin to the current token
                    discourseConnective.setBegin(token.getBegin());

                    // and add to the temporary list
                    discourseConnectives.add(discourseConnective);
                } else {
                    // look-up corresponding connective
                    DiscourseConnective existingConnective = findLastConnective(discourseConnectives,
                            relationId, connectiveType);

                    // set end from the previous token
                    if (prevToken == null) {
                        throw new IllegalStateException("No preceding token");
                    }
                    existingConnective.setEnd(prevToken.getEnd());
                }
            } else {
                // we have a discourse argument
                boolean isExplicit = element.getAttributeValue("type").equals("exp");
                if (discourseRelations.containsKey(relationId)
                        && discourseRelations.get(relationId) != isExplicit) {
                    throw new IllegalStateException("Relation " + relationId + " explicitness is inconsistent");
                } else {
                    // put id and relation type to the map
                    discourseRelations.put(relationId, isExplicit);
                }

                int argumentNumber = Integer.valueOf(element.getAttributeValue("arg"));

                String argumentType = element.getAttributeValue("t");

                if (isBegin) {
                    if (token == null) {
                        throw new IllegalStateException("Cannot begin discourse argument without token");
                    }

                    DiscourseArgument discourseArgument = new DiscourseArgument(jCas);
                    discourseArgument.setParentRelationId(relationId);
                    discourseArgument.setArgumentNumber(argumentNumber);
                    discourseArgument.setArgumentType(argumentType);

                    // set begin to current token
                    discourseArgument.setBegin(token.getBegin());

                    // add to the temporary list
                    discourseArguments.add(discourseArgument);
                } else {
                    // set end from the previous token
                    if (prevToken == null) {
                        throw new IllegalStateException("No preceding token");
                    }

                    DiscourseArgument existingArgument = findDiscourseArgument(discourseArguments, relationId,
                            argumentNumber);

                    if (existingArgument != null) {
                        existingArgument.setEnd(prevToken.getEnd());
                    }
                }
            }

            break;
        }
        case "attr": {
            // we have some relation etc. - do the annotation here!
            boolean isBegin = element.getAttributeValue("marker").equals("begin");
            Integer attrId = Integer.valueOf(element.getAttributeValue("id"));

            if (isBegin) {
                if (token == null) {
                    throw new IllegalStateException("Cannot begin discourse attribute without token");
                }
                DiscourseAttribution attribution = new DiscourseAttribution(jCas);
                attribution.setBegin(token.getBegin());
                attribution.setAttributeId(attrId);

                // add to the temporary list
                discourseAttributions.add(attribution);
            } else {
                if (prevToken == null) {
                    throw new IllegalStateException("No preceding token");
                }

                DiscourseAttribution attribution = findDiscourseAttribution(discourseAttributions, attrId);
                if (attribution != null) {
                    attribution.setEnd(prevToken.getEnd());
                }
            }

            break;
        }
        default:
            throw new IllegalArgumentException("Unknown element: " + element.getLocalName());
        }

        // and always move to the next element
        elementsPosition++;
    }

    // so what we have?
    if (verbose) {
        System.out.println("===== Discourse arguments");
        for (DiscourseArgument discourseArgument : discourseArguments) {
            System.out.println(discourseArgument);
            if (discourseArgument.getEnd() > 0) {
                System.out.println(discourseArgument.getCoveredText());
            } else {
                System.out.println("Missing end tag??");
            }
            System.out.println("---");
        }

        System.out.println("===== Discourse connectives");
        for (DiscourseConnective connective : discourseConnectives) {
            System.out.println(connective);
            System.out.println(connective.getCoveredText());
            System.out.println("---");
        }

        System.out.println("===== Discourse attributions");
        for (DiscourseAttribution attribution : discourseAttributions) {
            System.out.println(attribution);
            if (attribution.getEnd() > 0) {
                System.out.println(attribution.getCoveredText());
            }
            System.out.println("---");
        }

        System.out.println("Explicit/implicit discourseRelations");
        System.out.println(discourseRelations);
    }
    for (Map.Entry<Integer, Boolean> entry : discourseRelations.entrySet()) {
        int relationId = entry.getKey();
        boolean isExplicit = entry.getValue();

        // find arg1
        DiscourseArgument arg1 = null;
        for (DiscourseArgument discourseArgument : discourseArguments) {
            if (discourseArgument.getParentRelationId() == relationId
                    && discourseArgument.getArgumentNumber() == 1) {
                arg1 = discourseArgument;
                break;
            }
        }

        // find arg2
        DiscourseArgument arg2 = null;
        for (DiscourseArgument discourseArgument : discourseArguments) {
            if (discourseArgument.getParentRelationId() == relationId
                    && discourseArgument.getArgumentNumber() == 2) {
                arg2 = discourseArgument;
                break;
            }
        }

        if (arg1 != null && arg2 != null) {
            // check if they are properly annotated
            if (arg1.getEnd() > 0 && arg2.getEnd() > 0) {
                DiscourseRelation discourseRelation;

                // create either explicit or implicit relation
                if (isExplicit) {
                    discourseRelation = new ExplicitDiscourseRelation(jCas);

                    // so try to find all relevant connectives
                    List<DiscourseConnective> connectives = new ArrayList<>();
                    for (DiscourseConnective connective : discourseConnectives) {
                        if (connective.getParentRelationId() == relationId) {
                            connectives.add(connective);
                        }
                    }

                    // sort ascending
                    Collections.sort(connectives, new Comparator<DiscourseConnective>() {
                        @Override
                        public int compare(DiscourseConnective o1, DiscourseConnective o2) {
                            return Integer.compare(o1.getBegin(), o2.getBegin());
                        }
                    });

                    if (connectives.size() > 2) {
                        System.err.println("More than 2 connectives: " + connectives);
                    }

                    // add the first connective
                    if (connectives.size() == 1 || connectives.size() == 2) {
                        DiscourseConnective connective1 = connectives.get(0);
                        ((ExplicitDiscourseRelation) discourseRelation).setDiscourseConnective1(connective1);
                        connective1.addToIndexes();
                    }

                    // add the second connective
                    if (connectives.size() == 2) {
                        DiscourseConnective connective2 = connectives.get(0);
                        ((ExplicitDiscourseRelation) discourseRelation).setDiscourseConnective2(connective2);
                        connective2.addToIndexes();
                    }

                } else {
                    discourseRelation = new ImplicitDiscourseRelation(jCas);
                }
                discourseRelation.setRelationId(relationId);
                discourseRelation.setArg1(arg1);
                discourseRelation.setArg2(arg2);

                int begin = arg1.getBegin() < arg2.getBegin() ? arg1.getBegin() : arg2.getBegin();
                int end = arg1.getEnd() > arg2.getEnd() ? arg1.getEnd() : arg2.getEnd();

                discourseRelation.setBegin(begin);
                discourseRelation.setEnd(end);

                arg1.addToIndexes();
                arg2.addToIndexes();
                discourseRelation.addToIndexes();
            } else {
                System.err.println("Both arguments must be properly closed");
            }
        } else {
            System.err.println("Cannot find both arguments to relation " + relationId);
        }
    }

    // annotate all non-null Attributions
    for (DiscourseAttribution attribution : discourseAttributions) {
        if (attribution.getEnd() > 0) {
            attribution.addToIndexes();
        }
    }

    if (verbose) {
        for (DiscourseRelation discourseRelation : JCasUtil.select(jCas, DiscourseRelation.class)) {
            DiscourseDumpWriter.debugRelation(discourseRelation);
        }
    }
}

From source file:de.themoep.simpleteampvp.games.SimpleTeamPvPGame.java

/**
 * Balance the teams/* w w w. j  a va 2 s  .  com*/
 * @return <tt>true</tt> if game is in GameState.JOINING and players can be balanced
 */
public boolean balance() {
    if (getState() != GameState.JOINING)
        return false;

    plugin.getServer()
            .broadcastMessage(ChatColor.GREEN + "Ausbalancieren und Auffllen der Teams gestartet...");

    Map<Player, String> beforeBalance = new HashMap<>();
    List<Player> playersToJoin = new ArrayList<>();
    for (Player player : plugin.getServer().getOnlinePlayers()) {
        if (player.hasPermission(SimpleTeamPvP.BYPASS_PERM) || player.getGameMode() == GameMode.CREATIVE
                || player.getGameMode() == GameMode.SPECTATOR)
            continue;
        TeamInfo team = getTeam(player);
        if (team == null) {
            if (config.getRandomRegion() == null || config.getRandomRegion().contains(player.getLocation()))
                playersToJoin.add(player);
            beforeBalance.put(player, "");
        } else {
            beforeBalance.put(player, team.getName());
        }
    }
    plugin.getLogger().log(Level.INFO, "Players to join: " + playersToJoin.size());

    int totalPlayers = playersToJoin.size();
    for (TeamInfo team : config.getTeams().values()) {
        totalPlayers += team.getSize();
    }
    plugin.getLogger().log(Level.INFO, "Number of teams: " + config.getTeams().size());
    double perfectSize = (double) totalPlayers / (double) config.getTeams().size();

    plugin.getLogger().log(Level.INFO, "perfectSize: " + perfectSize);

    if (plugin.getServerTags() != null) {
        // Team key -> Tag
        Map<String, String> teamTags = new HashMap<>();

        for (TeamInfo team : config.getTeams().values()) {

            Map<String, Integer> tags = new HashMap<>();
            for (String playerName : team.getScoreboardTeam().getEntries()) {
                Player player = plugin.getServer().getPlayer(playerName);
                if (player == null)
                    continue;

                String tag = "no server";
                ServerInfo serverInfo = plugin.getServerTags().getPlayerServer(player);
                if (serverInfo != null) {
                    tag = serverInfo.getTag();
                }
                if (!tags.containsKey(tag)) {
                    tags.put(tag, 0);
                }
                tags.put(tag, tags.get(tag) + 1);
            }

            String teamTag = "no server";
            int tagCount = 0;
            for (Map.Entry<String, Integer> entry : tags.entrySet()) {
                if (entry.getValue() > tagCount) {
                    tagCount = entry.getValue();
                    teamTag = entry.getKey();
                }
            }

            teamTags.put(team.getName(), teamTag);
        }

        for (TeamInfo team : config.getTeams().values()) {
            // Filter out players that come from another server than the majority of the team
            // and remove them as long as the team is larger than the perfect size
            for (String playerName : team.getScoreboardTeam().getEntries()) {
                if (team.getSize() <= perfectSize + 0.5)
                    break;

                Player player = plugin.getServer().getPlayer(playerName);
                if (player == null)
                    continue;

                String tag = "no server";
                ServerInfo serverInfo = plugin.getServerTags().getPlayerServer(player);
                if (serverInfo != null) {
                    tag = serverInfo.getTag();
                }

                if (tag.equals(teamTags.get(team.getName())))
                    continue;

                plugin.getLogger().log(Level.INFO,
                        "[ST] Removed " + player.getName() + " from " + team.getName() + " (Step 1)");

                team.removePlayer(player);
                playersToJoin.add(player);
            }

            // Team still larger than the perfect size? Remove last joined player
            Deque<String> teamMates = new ArrayDeque<>(team.getScoreboardTeam().getEntries());
            while (team.getSize() > perfectSize + 0.5) {
                String name = teamMates.peekLast();
                Player player = plugin.getServer().getPlayer(name);
                if (player == null)
                    continue;

                team.removePlayer(player);
                plugin.getLogger().log(Level.INFO,
                        "[ST] Removed " + player.getName() + " from " + team.getName() + " (Step 2)");
                teamMates.pollLast();
                playersToJoin.add(player);
            }
        }

        // Add rest of players to teams from their server
        Iterator<Player> playerIterator = playersToJoin.iterator();
        while (playerIterator.hasNext()) {
            Player player = playerIterator.next();
            ServerInfo serverInfo = plugin.getServerTags().getPlayerServer(player);
            if (serverInfo != null && teamTags.containsValue(serverInfo.getTag())) {
                for (TeamInfo team : config.getTeams().values()) {
                    if (team.getSize() < perfectSize - 0.5 && teamTags.containsKey(team.getName())
                            && teamTags.get(team.getName()).equals(serverInfo.getTag())) {
                        team.addPlayer(player);
                        plugin.getLogger().log(Level.INFO,
                                "[ST] Added " + player.getName() + " to " + team.getName());
                        playerIterator.remove();
                        break;
                    }
                }
            }
        }
        plugin.getLogger().log(Level.INFO, "Players to join after servertags: " + playersToJoin.size());
    }

    // Remove players from teams that have more than the perfect size
    for (TeamInfo team : config.getTeams().values()) {
        for (String playerName : team.getScoreboardTeam().getEntries()) {
            if (team.getSize() <= perfectSize + 0.5)
                break;

            Player player = plugin.getServer().getPlayer(playerName);
            if (player == null)
                continue;

            plugin.getLogger().log(Level.INFO, "Removed " + player.getName() + " from " + team.getName());

            team.removePlayer(player);
            playersToJoin.add(player);
        }
    }

    Iterator<Player> playerIterator = playersToJoin.iterator();
    for (TeamInfo team : config.getTeams().values()) {
        while (playerIterator.hasNext()) {
            if (team.getSize() >= perfectSize - 0.5)
                break;

            Player player = playerIterator.next();
            team.addPlayer(player);
            plugin.getLogger().log(Level.INFO, "Added " + player.getName() + " to " + team.getName());
            playerIterator.remove();
        }
    }

    if (playerIterator.hasNext()) {
        plugin.getLogger().log(Level.INFO, "Adding " + playersToJoin.size()
                + " remaining players to teams according to their player count:");

        List<TeamInfo> teams = new ArrayList<>(config.getTeams().values());
        teams.sort((t1, t2) -> Integer.compare(t2.getSize(), t1.getSize()));

        for (TeamInfo team : teams) {
            while (playerIterator.hasNext()) {
                if (team.getSize() > perfectSize)
                    break;

                Player player = playerIterator.next();
                team.addPlayer(player);
                plugin.getLogger().log(Level.INFO,
                        "Added remaining player " + player.getName() + " to " + team.getName());
                playerIterator.remove();
            }
        }
    }

    if (playerIterator.hasNext()) {
        plugin.getLogger().log(Level.INFO,
                "Adding " + playersToJoin.size() + " remaining players to totally random teams:");
        Random r = new Random();
        List<TeamInfo> teams = new ArrayList<>(config.getTeams().values());
        while (playerIterator.hasNext()) {
            Player player = playerIterator.next();
            TeamInfo team = teams.get(r.nextInt(teams.size()));
            team.addPlayer(player);
            plugin.getLogger().log(Level.INFO,
                    "Added player " + player.getName() + " to " + team.getName() + " by random");
            playerIterator.remove();
        }
    }
    plugin.getLogger().log(Level.INFO, "All players joined! (" + playersToJoin.size() + ")");

    for (Map.Entry<Player, String> entry : beforeBalance.entrySet()) {
        TeamInfo team = getTeam(entry.getKey());
        if (team != null && !team.getName().equals(entry.getValue())) {
            Player player = null;
            for (Iterator<String> it = team.getScoreboardTeam().getEntries().iterator(); player == null
                    && it.hasNext();) {
                player = plugin.getServer().getPlayer(it.next());
            }
            if (player != null && team.getJoinRegion().contains(player.getLocation())) {
                entry.getKey().teleport(player);
            } else {
                entry.getKey().teleport(team.getJoinRegion().calculateMiddle().getLocation());
            }
        }
    }

    plugin.getServer().broadcastMessage(ChatColor.GREEN + "Teams ausbalanciert und aufgefllt!");

    state = GameState.WAITING;
    return true;
}

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

private void loadTriples() throws Exception {
    HashMap<String, Integer> propertyFrequency = new HashMap<>();
    HashSet<String> shortProperties = new HashSet<>();
    if (minPropertyLength > 1) {
        System.out.println(//from w ww  .j  av a2s .c  om
                "Finding propertys to be ignored because they have lenght less than " + minPropertyLength);
        int i = 0;
        try (BufferedReader in = new BufferedReader(new FileReader(basePathInput + "property_labels"))) {
            String l;
            while ((l = in.readLine()) != null) {
                i++;
                if (l.length() > 0) {
                    try {
                        StringTokenizer st = new StringTokenizer(l, "\t<> ");
                        String uri = st.nextToken().trim();
                        if (uri.startsWith("http")) {
                            String label = st.hasMoreTokens() ? st.nextToken().trim() : "";
                            if (label.length() < minPropertyLength && !shortProperties.contains(uri)) {
                                shortProperties.add(uri);
                                System.out
                                        .println("Property " + uri + " will be ignored, having label " + label);
                                propertyFrequency.put(uri, 0);
                            }
                        }
                    } catch (Exception e) {
                        System.out.println("Error at line " + i + ": " + l);
                        e.printStackTrace();
                    }
                }
            }
        }
        System.out.println(shortProperties.size() + " propertys will be ignored, having lenght less than "
                + minPropertyLength);
    }
    int maxNumberOfProperties = 100000;
    System.out.println("Finding the the " + maxNumberOfProperties
            + " most frequent propertys of the propertys whose label has at least two characters");
    try (BufferedReader in = new BufferedReader(new FileReader(basePathInput + "triples"))) {
        String l = in.readLine();
        int n = 0;
        while (l != null && l.length() > 0) {
            if (l.contains("classDegree")) {
                System.out.print("");
            }
            StringTokenizer st = new StringTokenizer(l, "<> \t");
            String subject = st.nextToken();
            String property = st.nextToken();
            String value = st.nextToken();
            if (subject.startsWith("http") && property.startsWith("http")
                    && !shortProperties.contains(property)) {
                if (value.startsWith("http") || value.startsWith("ftp:")) { //it is an entity
                    Integer c = propertyFrequency.get(property);
                    if (c == null) {
                        propertyFrequency.put(property, 1);
                    } else {
                        propertyFrequency.put(property, 1 + c);
                    }
                } else { //it is a literal
                    if (value.endsWith("^^")) { //it is a basic type
                        String type = StringEscapeUtils.unescapeJava(st.nextToken());
                        String literalType = basicTypesMapping.get(type);
                        if (literalType != null) {
                            Integer c = propertyFrequency.get(property);
                            if (c == null) {
                                propertyFrequency.put(property, 1);
                            } else {
                                propertyFrequency.put(property, 1 + c);
                            }
                        } else {
                            System.out.println("Basic type not recognized in " + l);
                        }
                    } else {
                        if (value.startsWith("\"")) { //it is a String
                            Integer c = propertyFrequency.get(property);
                            if (c == null) {
                                propertyFrequency.put(property, 1);
                            } else {
                                propertyFrequency.put(property, 1 + c);
                            }
                        } else {
                            System.out.println("Basic type not recognized in " + l);
                        }
                    }
                }
                n++;
                if (n % 1000000 == 0) {
                    System.out.println("Scanned " + (n / 1000000) + "M triples");
                }
            } else {
                //System.out.println("Invalid triple: " + l);
            }
            l = in.readLine();
        }
    }
    shortProperties = null;
    System.gc();
    ArrayList<Map.Entry<String, Integer>> f = new ArrayList<>(propertyFrequency.entrySet());
    Collections.sort(f, 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());
        }
    });
    int minFreq = 1;
    if (f.size() > maxNumberOfProperties) {
        minFreq = f.get(maxNumberOfProperties - 1).getValue();
        if (f.get(maxNumberOfProperties).equals(f.get(maxNumberOfProperties - 1))) {
            minFreq++;
        }
    }
    for (Map.Entry<String, Integer> e : f) {
        System.out.println(e.getKey() + "\t" + e.getValue());
    }
    System.out.println("Keeping propertys with at least " + minFreq + " occurrences");
    HashSet<String> acceptedProperties = new HashSet<>();
    for (Map.Entry<String, Integer> e : propertyFrequency.entrySet()) {
        if (e.getValue() >= minFreq) {
            acceptedProperties.add(e.getKey());
        }
    }
    System.out.println(acceptedProperties.size() + " propertys kept over " + f.size());
    f = null;
    propertyFrequency = null;
    System.gc();
    System.out.println("Mapping entities and property URIs to ids");
    int nEntityTriples = 0;
    HashMap<String, Integer> nLiteralTriples = new HashMap<>();
    for (String type : literalTypes) {
        nLiteralTriples.put(type, 0);
    }
    HashSet<String> unrecognizedBasicTypes = new HashSet<>();
    //count entity-valued and literal-valued triples
    //and
    //create the association between uris and ids for entities        
    try (BufferedReader in = new BufferedReader(new FileReader(basePathInput + "triples"))) {
        String l = in.readLine();
        int n = 0;
        while (l != null && l.length() > 0) {
            StringTokenizer st = new StringTokenizer(l, "<> \t");
            String subject = st.nextToken();
            String property = st.nextToken();
            if (!acceptedProperties.contains(property)) {
                l = in.readLine();
                continue;
            }
            String value = st.nextToken();
            if (subject.startsWith("http") && property.startsWith("http")) {
                Integer idSbj = getEntityIdFromUri(subject); //entityIdFromUri.get(subject);
                if (idSbj == null) {
                    idSbj = entityIdFromUriWithPrefix.size() + 1;//entityIdFromUri.size() + 1;
                    putEntityIdFromUri(subject, idSbj); //entityIdFromUri.put(subject, idSbj);
                }
                Integer idAttr = propertyIdFromUri.get(property);
                if (idAttr == null) {
                    idAttr = propertyIdFromUri.size() + 1;
                    propertyIdFromUri.put(property, idAttr);
                }
                if (value.startsWith("http") || value.startsWith("ftp:")) { //it is an entity
                    Integer idVal = getEntityIdFromUri(value); //entityIdFromUri.get(value);
                    if (idVal == null) {
                        idVal = entityIdFromUriWithPrefix.size() + 1;//entityIdFromUri.size() + 1;
                        putEntityIdFromUri(value, idVal);//entityIdFromUri.put(value, idVal);
                    }
                    Integer idInvAttr = propertyIdFromUri.get(property + "Inv");
                    if (idInvAttr == null) {
                        idInvAttr = propertyIdFromUri.size() + 1;
                        propertyIdFromUri.put(property + "Inv", idInvAttr);
                    }
                    nEntityTriples += 2;
                } else { //it is a literal
                    if (value.endsWith("^^")) { //it is a basic type
                        String type = StringEscapeUtils.unescapeJava(st.nextToken());
                        String literalType = basicTypesMapping.get(type);
                        if (literalType != null) {
                            nLiteralTriples.put(literalType, nLiteralTriples.get(literalType) + 1);
                        } else {
                            if (!unrecognizedBasicTypes.contains(type)) {
                                System.out.println("Unrecognized type: " + type);
                                System.out.println("in line: " + l);
                                unrecognizedBasicTypes.add(type);
                            }
                        }
                    } else {
                        if (value.startsWith("\"")) { //it is a String
                            nLiteralTriples.put(STRING, nLiteralTriples.get(STRING) + 1);
                        }
                    }
                }
                n++;
                if (n % 1000000 == 0) {
                    System.out.println("Loaded " + (n / 1000000) + "M triples");
                }
            } else {
                System.out.println("Invalid triple: " + l);
            }
            l = in.readLine();
        }
    }
    System.out.println("Number of triples with entity value: " + nEntityTriples);
    for (String type : literalTypes) {
        System.out.println("Number of triples with " + type + " value: " + nLiteralTriples.get(type));
    }
    entityTriplesSubjects = new int[nEntityTriples];
    entityTriplesProperties = new int[nEntityTriples];
    entityTriplesValues = new int[nEntityTriples];
    for (String type : literalTypes) {
        literalTriplesSubjects.put(type, new int[nLiteralTriples.get(type)]);
        literalTriplesProperties.put(type, new int[nLiteralTriples.get(type)]);
    }
    //load the triples into the arrays creaded above
    System.out.println("Loading triples");
    try (BufferedReader in = new BufferedReader(new FileReader(basePathInput + "triples"))) {
        String l = in.readLine();
        int n = 0;
        while (l != null && l.length() > 0) {
            StringTokenizer st = new StringTokenizer(l, "<> \t");
            String sbj = st.nextToken();
            String attr = st.nextToken();
            if (!acceptedProperties.contains(attr)) {
                l = in.readLine();
                continue;
            }
            String val = st.nextToken();
            if (sbj.startsWith("http") && attr.startsWith("http")) {
                if (val.startsWith("http") || val.startsWith("ftp:")) { //it is an entity
                    updateTriples(sbj, attr, val, null);
                } else { //it is a literal
                    if (val.endsWith("^^")) { //it is a basic type
                        String type = StringEscapeUtils.unescapeJava(st.nextToken());
                        String literalType = basicTypesMapping.get(type);
                        if (literalType != null) {
                            updateTriples(sbj, attr, null, literalType);
                        } else {
                            if (!unrecognizedBasicTypes.contains(type)) {
                                System.out.println("Unrecognized type: " + type);
                                System.out.println("in line: " + l);
                                unrecognizedBasicTypes.add(type);
                            }
                        }
                    } else {
                        if (val.startsWith("\"")) { //it is a String
                            updateTriples(sbj, attr, null, STRING);
                        } else {
                            System.out.println("Unexpected line: " + l);
                        }
                    }
                }
                n++;
                if (n % 1000000 == 0) {
                    System.out.println("Loaded " + (n / 1000000) + "M triples");
                }
            } else {
                System.out.println("Invalid triple: " + l);
            }
            l = in.readLine();
        }
    }
    System.out.println("Entity value triples: " + entityTriplesSubjects.length);
    for (String type : literalTriplesSubjects.keySet()) {
        System.out.println(type + " value triples: " + literalTriplesSubjects.get(type).length);
    }
    propertyUri = new String[propertyIdFromUri.size() + 1];
    for (Map.Entry<String, Integer> e : propertyIdFromUri.entrySet()) {
        propertyUri[e.getValue()] = e.getKey();
    }
    entityUriWithPrefix = new String[entityIdFromUriWithPrefix.size() + 1];
    for (Map.Entry<String, Integer> e : entityIdFromUriWithPrefix.entrySet()) {
        entityUriWithPrefix[e.getValue()] = e.getKey();
    }
    //entityUri = new String[entityIdFromUri.size() + 1];
    //for (Map.Entry<String, Integer> e : entityIdFromUri.entrySet()) {
    //    entityUri[e.getValue()] = e.getKey();
    //}
    entityLabels = new HashSet[entityIdFromUriWithPrefix.size() + 1]; //entityLabels = new HashSet[entityIdFromUri.size() + 1];
    entityClasses = new HashSet[entityIdFromUriWithPrefix.size() + 1]; //entityClasses = new HashSet[entityIdFromUri.size() + 1];
    propertyLabels = new HashSet[propertyIdFromUri.size() + 1];
    entityOutProperties = new HashSet[entityIdFromUriWithPrefix.size() + 1]; //entityOutProperties = new HashSet[entityIdFromUri.size() + 1];
    entityInProperties = new HashSet[entityIdFromUriWithPrefix.size() + 1]; //entityInProperties = new HashSet[entityIdFromUri.size() + 1];
    propertyOutProperties = new HashSet[propertyIdFromUri.size() + 1];
    propertyInProperties = new HashSet[propertyIdFromUri.size() + 1];
    propertyHasLiteralRange = new boolean[propertyIdFromUri.size() + 1];
    propertyCount = new int[propertyIdFromUri.size() + 1];
}