Example usage for java.util SortedMap containsKey

List of usage examples for java.util SortedMap containsKey

Introduction

In this page you can find the example usage for java.util SortedMap containsKey.

Prototype

boolean containsKey(Object key);

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:org.omnaest.utils.table.TableTest.java

@Test
public void testIndexOfArbitraryKeyExtractor() {
    Table<String> table = this.filledTable(100, 5);

    KeyExtractor<Integer, RowDataReader<String>> keyExtractor = new KeyExtractor<Integer, RowDataReader<String>>() {
        private static final long serialVersionUID = -4201644938610833630L;

        @Override/*from   w  ww .j av  a  2 s  .  co m*/
        public Integer extractKey(RowDataReader<String> rowDataReader) {
            String[] elements = rowDataReader.getElements();
            String[] tokens = elements[1].split(":");
            return Integer.valueOf(tokens[0]);
        }
    };
    SortedMap<Integer, Set<Row<String>>> sortedMap = table.index().of(keyExtractor);
    {
        assertNotNull(sortedMap);
        assertEquals(table.rowSize(), sortedMap.size());
        assertTrue(sortedMap.containsKey(0));
    }

    table.removeRow(0);
    {
        assertFalse(sortedMap.containsKey(0));
        assertTrue(sortedMap.containsKey(1));
        assertFalse(sortedMap.containsKey(101));

        table.setElement(0, 1, "101:88");
        assertTrue(sortedMap.containsKey(101));

        Set<Row<String>> rowSet = sortedMap.get(101);
        assertEquals(1, rowSet.size());
    }
    {
        assertSame(sortedMap, table.index().of(keyExtractor));
    }

    table.setRowElements(1, "0:0", "200:0");
    {
        assertTrue(sortedMap.containsKey(200));
    }
    {
        SortedMap<Integer, Set<Row<String>>> tailMap = sortedMap.tailMap(90);
        assertEquals(100 - 90 + 2, tailMap.size());
        assertEquals(90, tailMap.firstKey().intValue());
        assertEquals(200, tailMap.lastKey().intValue());
    }
    {
        SortedMap<Integer, Set<Row<String>>> headMap = sortedMap.headMap(10);
        assertEquals(9 - 2, headMap.size());
        assertEquals(3, headMap.firstKey().intValue());
        assertEquals(9, headMap.lastKey().intValue());
    }
    {
        table.clear();
        assertTrue(sortedMap.isEmpty());
    }
}

From source file:com.palantir.atlasdb.transaction.impl.SnapshotTransaction.java

@Override
public Map<Cell, byte[]> get(String tableName, Set<Cell> cells) {
    Stopwatch watch = Stopwatch.createStarted();
    checkGetPreconditions(tableName);/*from w  ww .j  ava 2s .  c o  m*/
    if (Iterables.isEmpty(cells)) {
        return ImmutableMap.of();
    }

    Map<Cell, byte[]> result = Maps.newHashMap();
    SortedMap<Cell, byte[]> writes = writesByTable.get(tableName);
    if (writes != null) {
        for (Cell cell : cells) {
            if (writes.containsKey(cell)) {
                result.put(cell, writes.get(cell));
            }
        }
    }

    // We don't need to read any cells that were written locally.
    result.putAll(getFromKeyValueService(tableName, Sets.difference(cells, result.keySet())));

    if (perfLogger.isDebugEnabled()) {
        perfLogger.debug("get({}, {} cells) found {} cells (some possibly deleted), took {} ms", tableName,
                cells.size(), result.size(), watch.elapsed(TimeUnit.MILLISECONDS));
    }
    validateExternalAndCommitLocksIfNecessary(tableName);
    return Maps.filterValues(result, Predicates.not(Value.IS_EMPTY));
}

From source file:org.onebusaway.community_transit_gtfs.CommunityTransitGtfsFactory.java

/**
 * Borrowed from OBA StopTimeEntriesFactory.
 * We have a list of StopTimes, along with their distance traveled along their
 * trip/block. For any StopTime that has either an arrival or a departure
 * time, we add it to the SortedMaps of arrival and departure times by
 * distance traveled.//  w  w w . ja v a2 s .  com
 * 
 * @param stopTimes
 * @param distances
 * @param arrivalTimesByDistanceTraveled
 */
private void populateArrivalAndDepartureTimesByDistanceTravelledForStopTimes(List<StopTime> stopTimes,
        double[] distances, SortedMap<Double, Integer> scheduleTimesByDistanceTraveled) {

    for (int i = 0; i < stopTimes.size(); i++) {

        StopTime stopTime = stopTimes.get(i);
        double d = distances[i];

        // We introduce distinct arrival and departure distances so that our
        // scheduleTimes map might have entries for arrival and departure times
        // that are not the same at a given stop
        double arrivalDistance = d;
        double departureDistance = d + 1e-6;

        /**
         * For StopTime's that have the same distance travelled, we keep the min
         * arrival time and max departure time
         */
        if (stopTime.getArrivalTime() >= 0) {
            if (!scheduleTimesByDistanceTraveled.containsKey(arrivalDistance)
                    || scheduleTimesByDistanceTraveled.get(arrivalDistance) > stopTime.getArrivalTime())
                scheduleTimesByDistanceTraveled.put(arrivalDistance, stopTime.getArrivalTime());
        }

        if (stopTime.getDepartureTime() >= 0)
            if (!scheduleTimesByDistanceTraveled.containsKey(departureDistance)
                    || scheduleTimesByDistanceTraveled.get(departureDistance) < stopTime.getDepartureTime())
                scheduleTimesByDistanceTraveled.put(departureDistance, stopTime.getDepartureTime());
    }
}

From source file:com.github.fauu.natrank.service.RankingServiceImpl.java

private void calculateTeamRatingsAndRankChanges(List<Match> matches) throws DataAccessException {
    teamRatingRepository.deleteAll();//from w  w  w.ja v  a  2  s  .  com
    teamRankRepository.deleteAll();

    List<TeamRating> ratings = new LinkedList<>();
    List<TeamRank> ranks = new LinkedList<>();
    Map<Integer, RankedTeam> rankedTeamsByTeamId = new HashMap();
    List<Team> teams = teamRepository.findAll();
    SortedMap<Integer, Integer> initialRatings = new TreeMap<>();

    for (int passNo = 0; passNo < 2; passNo++) {
        if (passNo == 1) {
            ratings.clear();

            for (Team team : teams) {
                team.getRatings().clear();
            }
        }

        for (Match match : matches) {
            List<Team> matchTeams = new ArrayList<>();
            matchTeams.add(match.getTeam1());
            matchTeams.add(match.getTeam2());

            for (Team team : matchTeams) {
                if (team.getRatings().size() == 0) {
                    team.setHomeAdvantageCoefficient(INITIAL_HOME_ADVANTAGE_COEFFICIENT);
                    TeamRating rating = new TeamRating();
                    rating.setDate(match.getDate());
                    rating.setTeam(team);
                    rating.setChange(0);
                    rating.setProvisional(true);

                    if (!initialRatings.containsKey(team.getId())) {
                        for (int year : DEFAULT_RATINGS_UPTO_YEAR.keySet()) {
                            if (match.getDate().getYear() < year) {
                                initialRatings.put(team.getId(), DEFAULT_RATINGS_UPTO_YEAR.get(year));

                                break;
                            }
                        }
                    }

                    rating.setValue(initialRatings.get(team.getId()));

                    team.getRatings().add(rating);
                }
            }

            List<Integer> matchTeamRatings = new ArrayList<>();
            matchTeamRatings.add(matchTeams.get(0).getCurrentRating().getValue());
            matchTeamRatings.add(matchTeams.get(1).getCurrentRating().getValue());
            List<Integer> matchTeamRatingsAdjusted = new ArrayList<>(matchTeamRatings);

            Team winnerTeam = match.getWinnerTeam();
            double marginOfVictoryCoefficient;
            double matchResultCoefficient = 0;

            if (winnerTeam != null) {
                marginOfVictoryCoefficient = Math.sqrt(Math.abs(match.getTeam1Goals() - match.getTeam2Goals()));

                if (winnerTeam == matchTeams.get(0)) {
                    matchResultCoefficient = 1;
                    matchTeamRatingsAdjusted.set(0, matchTeamRatingsAdjusted.get(0)
                            + (int) Math.round(matchTeams.get(0).getHomeAdvantageCoefficient()));
                } else if (winnerTeam == matchTeams.get(1)) {
                    matchResultCoefficient = 0;
                    matchTeamRatingsAdjusted.set(1, matchTeamRatingsAdjusted.get(1)
                            + (int) Math.round(matchTeams.get(1).getHomeAdvantageCoefficient()));
                }
            } else {
                marginOfVictoryCoefficient = 1;
                matchResultCoefficient = 0.5;
            }

            double exponent = (-1 * (matchTeamRatingsAdjusted.get(0) - matchTeamRatingsAdjusted.get(1)))
                    / 444.0;
            double expectedMatchResultCoefficient = 1 / (Math.pow(10, exponent) + 1);

            double team1RatingChange = match.getType().getWeight() * marginOfVictoryCoefficient
                    * (matchResultCoefficient - expectedMatchResultCoefficient);
            long team1RatingChangeRounded = Math.round(team1RatingChange);

            List<Integer> matchTeamRatingChanges = new ArrayList<>();
            matchTeamRatingChanges.add((int) team1RatingChangeRounded);
            matchTeamRatingChanges.add(-1 * (int) team1RatingChangeRounded);

            for (int i = 0; i < 2; i++) {
                Team currentTeam = matchTeams.get(i);

                int ratingChangeModifier = 1;
                if (passNo == 0 && currentTeam.getRatings().size() - 1 < NUM_TRIAL_MATCHES) {
                    ratingChangeModifier = TRIAL_RATING_MODIFIER;
                }

                int currentTeamOldRating = matchTeamRatings.get(i);
                matchTeamRatings.set(i,
                        currentTeamOldRating + ratingChangeModifier * matchTeamRatingChanges.get(i));

                TeamRating newRating = new TeamRating();
                newRating.setDate(match.getDate());
                newRating.setTeam(matchTeams.get(i));
                newRating.setMatch(match);
                newRating.setValue(matchTeamRatings.get(i));
                newRating.setChange(matchTeamRatingChanges.get(i));

                if (passNo == 1 && currentTeam.getRatings().size() < NUM_TRIAL_MATCHES) {
                    newRating.setProvisional(true);
                }

                matchTeams.get(i).setHomeAdvantageCoefficient(matchTeams.get(i).getHomeAdvantageCoefficient()
                        + 0.075 * matchTeamRatingChanges.get(i));

                if (i == 0) {
                    match.setTeam1Rating(newRating.getValue());
                    match.setTeam1RatingChange(newRating.getChange());
                } else if (i == 1) {
                    match.setTeam2Rating(newRating.getValue());
                    match.setTeam2RatingChange(newRating.getChange());
                }

                ratings.add(newRating);

                currentTeam.getRatings().add(newRating);

                if (passNo == 1 && (currentTeam.getRatings().size() - 1) >= NUM_TRIAL_MATCHES) {
                    List<RankedTeam> rankedTeamsToProcess = new LinkedList<>();

                    boolean isFirstEntryOfCurrentTeam = false;
                    if (!rankedTeamsByTeamId.containsKey(currentTeam.getId())) {
                        RankedTeam newRankedTeam = new RankedTeam();

                        newRankedTeam.setTeam(currentTeam);
                        newRankedTeam.setRating(currentTeam.getCurrentRating().getValue());
                        newRankedTeam.setRank(rankedTeamsByTeamId.size() + 1);

                        rankedTeamsByTeamId.put(currentTeam.getId(), newRankedTeam);

                        currentTeamOldRating = 0;

                        isFirstEntryOfCurrentTeam = true;
                    }

                    int currentTeamCurrentRating = currentTeam.getCurrentRating().getValue();

                    int currentTeamRatingChange = currentTeamCurrentRating - currentTeamOldRating;

                    if (currentTeamRatingChange != 0) {
                        int currentTeamHighRating = currentTeamRatingChange >= 0 ? currentTeamCurrentRating
                                : currentTeamOldRating;
                        int currentTeamLowRating = currentTeamRatingChange < 0 ? currentTeamCurrentRating
                                : currentTeamOldRating;

                        int currentTeamRank = rankedTeamsByTeamId.get(currentTeam.getId()).getRank();
                        for (Map.Entry<Integer, RankedTeam> rankedTeamEntry : rankedTeamsByTeamId.entrySet()) {
                            if (rankedTeamEntry.getKey().equals(currentTeam.getId())) {
                                rankedTeamEntry.getValue().setRating(currentTeamCurrentRating);
                            }

                            int entryTeamRating = rankedTeamEntry.getValue().getRating();

                            int entryTeamRank = rankedTeamEntry.getValue().getRank();
                            if ((currentTeamHighRating >= entryTeamRating)
                                    && (currentTeamLowRating <= entryTeamRating)
                                    && !((currentTeamRatingChange > 0)
                                            && (entryTeamRating == currentTeamLowRating)
                                            && (entryTeamRank > currentTeamRank))
                                    && !((currentTeamRatingChange < 0)
                                            && (entryTeamRating == currentTeamHighRating)
                                            && (entryTeamRank < currentTeamRank))) {
                                rankedTeamsToProcess.add(rankedTeamEntry.getValue());
                            }
                        }

                        if (isFirstEntryOfCurrentTeam || rankedTeamsToProcess.size() > 1) {
                            int otherTeamsRankChange = currentTeamRatingChange > 0 ? 1 : -1;
                            int currentTeamRankChange = -1 * otherTeamsRankChange
                                    * (rankedTeamsToProcess.size() - 1);
                            for (RankedTeam rankedTeam : rankedTeamsToProcess) {
                                int rankChange = rankedTeam.getTeam() == currentTeam ? currentTeamRankChange
                                        : otherTeamsRankChange;

                                rankedTeam.setRank(rankedTeam.getRank() + rankChange);

                                TeamRank newTeamRankEntry = new TeamRank();
                                newTeamRankEntry.setDate(match.getDate());
                                newTeamRankEntry.setTeam(rankedTeam.getTeam());
                                newTeamRankEntry.setValue(rankedTeam.getRank());
                                if (!(rankedTeam.getTeam() == currentTeam) || !isFirstEntryOfCurrentTeam) {
                                    newTeamRankEntry.setChange(-1 * rankChange);
                                }

                                if (rankedTeam.getTeam() == match.getTeam1()) {
                                    match.setTeam1Rank(newTeamRankEntry.getValue());
                                    match.setTeam1RankChange(newTeamRankEntry.getChange());
                                } else if (rankedTeam.getTeam() == match.getTeam2()) {
                                    match.setTeam2Rank(newTeamRankEntry.getValue());
                                    match.setTeam2RankChange(newTeamRankEntry.getChange());
                                }

                                ranks.add(newTeamRankEntry);
                            }
                        } else {
                            if (i == 0) {
                                match.setTeam1Rank(rankedTeamsByTeamId.get(currentTeam.getId()).getRank());
                                match.setTeam1RankChange(0);
                            } else if (i == 1) {
                                match.setTeam2Rank(rankedTeamsByTeamId.get(currentTeam.getId()).getRank());
                                match.setTeam2RankChange(0);
                            }
                        }
                    }
                }

                if (passNo == 0 && (matchTeams.get(i).getRatings().size() - 1 < NUM_TRIAL_MATCHES)) {
                    initialRatings.put(matchTeams.get(i).getId(), newRating.getValue());
                }
            }
        }
    }

    matchRepository.save(matches);
    teamRatingRepository.save(ratings);
    teamRankRepository.save(ranks);
}

From source file:de.uni_potsdam.hpi.asg.logictool.mapping.SequenceBasedAndGateDecomposer.java

private Map<Integer, List<Partition>> getPartitions(Set<Signal> signals, int startgatesize) {
    // cost function
    SortedMap<Integer, List<Partition>> retVal = new TreeMap<>(Collections.reverseOrder());
    Set<Set<Set<Signal>>> parts = getTailCombinations(signals);
    if (parts == null) {
        return null;
    }//from  w w  w .ja  v  a 2s  .  c  o  m
    for (Set<Set<Signal>> partition : parts) {
        int cost = 0;
        Set<PartitionPart> parts2 = new HashSet<>();
        for (Set<Signal> partpart : partition) {
            parts2.add(new PartitionPart(partpart));
            if (partpart.size() != 1) {
                cost += partpart.size();
            }
        }
        if (partition.size() != 1) {
            cost += partition.size();
        }

        if (!retVal.containsKey(cost)) {
            retVal.put(cost, new ArrayList<Partition>());
        }
        retVal.get(cost).add(new Partition(parts2, cost));
    }

    //      System.out.println("Startgatesize: " + startgatesize);
    // filter too large
    List<Partition> rmPart = new ArrayList<>();
    List<Integer> rmKey = new ArrayList<>();
    for (Entry<Integer, List<Partition>> entry : retVal.entrySet()) {
        //         System.out.println(entry.getKey());
        rmPart.clear();
        for (Partition p : entry.getValue()) {
            //            System.out.println("\t" + p.toString());
            if (p.getPartition().size() >= startgatesize) {
                //               System.out.println("Rm: " + p);
                rmPart.add(p);
                continue;
            }
            for (PartitionPart p2 : p.getPartition()) {
                if (p2.getPart().size() >= startgatesize) {
                    //                  System.out.println("Rm: " + p);
                    rmPart.add(p);
                    continue;
                }
            }
        }
        entry.getValue().removeAll(rmPart);
        if (entry.getValue().isEmpty()) {
            rmKey.add(entry.getKey());
        }
    }
    for (int i : rmKey) {
        retVal.remove(i);
    }

    return retVal;
}

From source file:org.kuali.kra.budget.calculator.BudgetCalculationServiceImpl.java

protected SortedMap<BudgetCategoryType, List<CostElement>> categorizeObjectCodesByCategory(Budget budget) {
    SortedMap<CostElement, List<BudgetDecimal>> objectCodeTotals = budget.getObjectCodeTotals();
    SortedMap<BudgetCategoryType, List<CostElement>> objectCodeListByBudgetCategoryType = new TreeMap<BudgetCategoryType, List<CostElement>>();

    for (CostElement objectCode : objectCodeTotals.keySet()) {
        objectCode.refreshReferenceObject("budgetCategory");
        if (objectCode.getBudgetCategory() != null) {
            objectCode.getBudgetCategory().refreshReferenceObject("budgetCategoryType");
            objectCode.setBudgetCategoryTypeCode(objectCode.getBudgetCategory().getBudgetCategoryTypeCode());
        }//  w  w  w . jav  a  2s  . c om
        if (!objectCodeListByBudgetCategoryType
                .containsKey(objectCode.getBudgetCategory().getBudgetCategoryType())) {
            List<CostElement> filteredObjectCodes = filterObjectCodesByBudgetCategoryType(
                    objectCodeTotals.keySet(), objectCode.getBudgetCategoryTypeCode());
            objectCodeListByBudgetCategoryType.put(objectCode.getBudgetCategory().getBudgetCategoryType(),
                    filteredObjectCodes);
        }
    }

    return objectCodeListByBudgetCategoryType;
}

From source file:tajo.master.GlobalPlanner.java

private Map<String, Map<ScanNode, List<Fragment>>> hashFragments(Map<ScanNode, List<Fragment>> fragMap) {
    SortedMap<String, Map<ScanNode, List<Fragment>>> hashed = new TreeMap<String, Map<ScanNode, List<Fragment>>>();
    String key;/* w ww.j  av  a  2s .c  om*/
    Map<ScanNode, List<Fragment>> m = null;
    List<Fragment> fragList = null;
    for (Entry<ScanNode, List<Fragment>> e : fragMap.entrySet()) {
        for (Fragment f : e.getValue()) {
            key = f.getPath().getName();
            if (hashed.containsKey(key)) {
                m = hashed.get(key);
            } else {
                m = new HashMap<ScanNode, List<Fragment>>();
            }
            if (m.containsKey(e.getKey())) {
                fragList = m.get(e.getKey());
            } else {
                fragList = new ArrayList<Fragment>();
            }
            fragList.add(f);
            m.put(e.getKey(), fragList);
            hashed.put(key, m);
        }
    }

    return hashed;
}

From source file:fr.aliacom.obm.common.calendar.CalendarBindingImpl.java

@VisibleForTesting
void inheritsParticipationOnExceptions(Event before, Event event) {
    Set<Event> beforeExceptions = before.getEventsExceptions();
    SortedMap<Event, Event> eventExceptions = buildSortedMap(event.getEventsExceptions());

    for (Event beforeException : beforeExceptions) {
        if (eventExceptions.containsKey(beforeException)) {
            inheritsParticipationFromExistingEventForObmUsers(beforeException,
                    eventExceptions.get(beforeException));
        }/* ww  w .  ja v  a  2 s.c o  m*/
    }
}

From source file:org.omnaest.utils.table.TableTest.java

@SuppressWarnings({ "unchecked", "cast" })
@Test/*from w  w  w  .  j a v a 2  s . c o m*/
public void testIndexOfArbitraryKeyExtractorWithValueExtractor() {
    Table<String> table = this.filledTable(100, 5);

    KeyExtractor<Integer, RowDataReader<String>> keyExtractor = new KeyExtractor<Integer, RowDataReader<String>>() {
        private static final long serialVersionUID = -7714884390309847394L;

        @Override
        public Integer extractKey(RowDataReader<String> rowDataReader) {
            String[] elements = rowDataReader.getElements();
            String[] tokens = elements[1].split(":");
            return Integer.valueOf(tokens[0]);
        }
    };
    ValueExtractor<Integer, Set<String[]>> valueExtractor = new ValueExtractor<Integer, Set<String[]>>() {
        @Override
        public Integer extractValue(Set<String[]> elementsSet) {
            final String[] elements = IterableUtils.firstElement(elementsSet);
            final String[] tokens = elements[1].split(":");
            return Integer.valueOf(tokens[1]);
        }
    };

    SortedMap<Integer, Integer> sortedMap = table.index().of(keyExtractor, valueExtractor,
            (Comparator<Integer>) ComparatorUtils.reversedComparator(ComparatorUtils.NATURAL_COMPARATOR));
    {
        assertNotNull(sortedMap);
        assertEquals(table.rowSize(), sortedMap.size());
        assertTrue(sortedMap.containsKey(0));
    }

    table.removeRow(0);
    {
        assertFalse(sortedMap.containsKey(0));
        assertTrue(sortedMap.containsKey(1));
        assertFalse(sortedMap.containsKey(101));

        table.setElement(0, 1, "101:88");
        assertTrue(sortedMap.containsKey(101));

        Integer columnIndex = sortedMap.get(101);
        assertEquals(88, columnIndex.intValue());
    }

}

From source file:org.kuali.coeus.common.budget.impl.calculator.BudgetCalculationServiceImpl.java

/**
 * This method is to get list of line items based on budget category type grouped by cost element.
 *//*from www  . j a v  a2  s.c o  m*/
private SortedMap<CostElement, List<BudgetLineItem>> getBudgetSummaryUniqueLineItemCostElementsForBudgetCategory(
        List<BudgetLineItem> budgetLineItems, String budgetCategoryTypeCode) {
    SortedMap<CostElement, List<BudgetLineItem>> uniqueLineItemCostElements = new TreeMap<>();
    for (BudgetLineItem budgetLineItem : budgetLineItems) {
        CostElement costElement = budgetLineItem.getCostElementBO();
        String costElementBudgetCategoryTypeCode = costElement.getBudgetCategory().getBudgetCategoryTypeCode();
        if (costElementBudgetCategoryTypeCode.equalsIgnoreCase(budgetCategoryTypeCode)) {
            if (!uniqueLineItemCostElements.containsKey(costElement)) {
                uniqueLineItemCostElements.put(costElement, new ArrayList<>());
            }
            uniqueLineItemCostElements.get(costElement).add(budgetLineItem);
        }
    }
    return uniqueLineItemCostElements;
}