Java Code Examples for java.util.Comparator.comparingInt()

The following are Jave code examples for showing how to use comparingInt() of the java.util.Comparator class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: dxram   File: NameserviceHashTable.java   View Source Code Vote up 6 votes
/**
 * Print all tuples in IDHashTable sorted
 */
public final void printSorted() {
    int iter;
    Collection<Entry> list;

    list = new TreeSet<>(Comparator.comparingInt(p_entryA -> p_entryA.m_key));

    for (int i = 0; i < m_elementCapacity; i++) {
        iter = getKey(i);
        if (iter != 0) {
            list.add(new Entry(iter, getValue(i)));
        }
    }

    for (Entry entry : list) {
        System.out.println("Key: " + entry.m_key + ", value: " + ChunkID.toHexString(entry.m_value));
    }
}
 
Example 2
Project: ULCRS   File: ULCCourseRequirements.java   View Source Code Vote up 6 votes
public CourseRequirements toCourseRequirements(HashMap<Integer, Shift> shifts) {
    Set<Shift> requiredShifts = new TreeSet<>(Comparator.comparingInt(Shift::getId));
    Map<Integer, Integer> numTutorsPerShift = new HashMap<>();

    this.specifics.forEach(specific -> {
        int shiftId = specific.getShiftId();
        int numTutors = specific.getNumTutors();

        Shift shift = shifts.get(shiftId);
        if (shift != null) {
            requiredShifts.add(shift);
            numTutorsPerShift.put(shift.getId(), numTutors);
        }
    });

    CourseIntensity intensity = CourseIntensity.fromString(this.intensity);

    return new CourseRequirements(requiredShifts, this.timesPerWeek, 0, intensity, numTutorsPerShift, this.numTutors);
}
 
Example 3
Project: jpa2ddl   File: FileResolver.java   View Source Code Vote up 6 votes
static List<Path> resolveExistingMigrations(File migrationsDir, boolean reversed, boolean onlySchemaMigrations) {
	if (!migrationsDir.exists()) {
		migrationsDir.mkdirs();
	}

	File[] files = migrationsDir.listFiles();

	if (files == null) {
		return Collections.emptyList();
	}

	Comparator<Path> pathComparator = Comparator.comparingInt(FileResolver::compareVersionedMigrations);
	if (reversed) {
		pathComparator = pathComparator.reversed();
	}
	return Arrays.stream(files)
			.map(File::toPath)
			.filter(path -> !onlySchemaMigrations || SCHEMA_FILENAME_PATTERN.matcher(path.getFileName().toString()).matches())
			.sorted(pathComparator)
			.collect(Collectors.toList());
}
 
Example 4
Project: FreeCol   File: IndianSettlement.java   View Source Code Vote up 5 votes
/**
 * Chooses a type of goods for some of the natives in a settlement
 * to manufacture.
 * Simple rule: choose the refined goods that is the greatest shortage
 * for which there is a surplus of the raw material.
 *
 * @return A {@code GoodsType} to manufacture, or null if
 *      none suitable.
 */
private GoodsType goodsToMake() {
    final ToIntFunction<GoodsType> deficit = cacheInt(gt ->
        getWantedGoodsAmount(gt) - getGoodsCount(gt));
    final Predicate<GoodsType> goodsPred = gt ->
        gt.isRawMaterial()
            && gt.getOutputType() != null
            && !gt.getOutputType().isBreedable()
            && gt.getOutputType().isStorable()
            && deficit.applyAsInt(gt) < 0
            && deficit.applyAsInt(gt.getOutputType()) > 0;
    final Comparator<GoodsType> comp = Comparator.comparingInt(deficit);
    return maximize(getSpecification().getGoodsTypeList(), goodsPred, comp);
}
 
Example 5
Project: freecol   File: NewUnitPanel.java   View Source Code Vote up 5 votes
/**
 * The constructor to use.
 *
 * @param freeColClient The {@code FreeColClient} for the game.
 * @param layout The {@code LayoutManager} to use.
 * @param label The label for the panel.
 * @param units A list of {@code UnitType}s to offer.
 */
public NewUnitPanel(FreeColClient freeColClient, LayoutManager layout,
                    String label, List<UnitType> units) {
    super(freeColClient, layout);

    this.question = new JLabel(label);
    this.units.addAll(units);
    final Europe europe = getMyPlayer().getEurope();
    this.priceComparator = Comparator.comparingInt((UnitType ut) ->
        europe.getUnitPrice(ut));

    okButton.setText(Messages.message("close"));

    update();
}
 
Example 6
Project: FreeCol   File: Player.java   View Source Code Vote up 5 votes
/**
 * Get the most valuable goods available in one of the player's
 * colonies for the purposes of choosing a threat-to-boycott.  The
 * goods must not currently be boycotted, the player must have
 * traded in it, and the amount to be discarded will not exceed
 * GoodsContainer.CARGO_SIZE.
 *
 * @return A goods object, or null if nothing suitable found.
 */
public Goods getMostValuableGoods() {
    if (!isEuropean()) return null;
    final Predicate<Goods> boycottPred = g ->
        getArrears(g.getType()) <= 0 && hasTraded(g.getType());
    final Comparator<Goods> tradedValueComp = Comparator.comparingInt(g ->
        market.getSalePrice(g.getType(),
            Math.min(g.getAmount(), GoodsContainer.CARGO_SIZE)));
    return maximize(flatten(getColonies(),
                            c -> c.getCompactGoodsList().stream()),
                    boycottPred, tradedValueComp);
}
 
Example 7
Project: FreeCol   File: SimpleMapGenerator.java   View Source Code Vote up 5 votes
/**
 * Find the closest territory to a given tile from a list of choices.
 *
 * @param tile The {@code Tile} to search from.
 * @param territories The list of {@code Territory}s to choose from.
 * @return The closest {@code Territory} found, or null if none.
 */
private Territory getClosestTerritory(final Tile tile,
                                      List<Territory> territories) {
    final Map map = tile.getMap();
    final Comparator<Territory> comp = Comparator.comparingInt(t ->
        map.getDistance(tile, t.getCenterTile(map)));
    return minimize(territories, comp);
}
 
Example 8
Project: freecol   File: ServerIndianSettlement.java   View Source Code Vote up 5 votes
/**
 * Updates the most hated nation of this settlement.
 * Needs to be public so it can be set by backwards compatibility code
 * in FreeColServer.loadGame.
 *
 * -til: This might change the tile appearance.
 *
 * @return True if the most hated nation changed.
 */
public boolean updateMostHated() {
    final Player old = this.mostHated;
    final Predicate<Player> hatedPred = p -> {
        Tension alarm = getAlarm(p);
        return alarm != null && alarm.getLevel() != Tension.Level.HAPPY;
    };
    final Comparator<Player> mostHatedComp
        = Comparator.comparingInt(p -> getAlarm(p).getValue());
    this.mostHated = maximize(getGame().getLiveEuropeanPlayers(),
                              hatedPred, mostHatedComp);
    return this.mostHated != old;
}
 
Example 9
Project: jdk8u-jdk   File: BasicTest.java   View Source Code Vote up 5 votes
public void testIntComparator() {
    Thing[] things = new Thing[intValues.length];
    for (int i=0; i<intValues.length; i++)
        things[i] = new Thing(intValues[i], 0L, 0.0, null);
    Comparator<Thing> comp = Comparator.comparingInt(new ToIntFunction<Thing>() {
        @Override
        public int applyAsInt(Thing thing) {
            return thing.getIntField();
        }
    });

    assertComparisons(things, comp, comparisons);
}
 
Example 10
Project: freecol   File: Player.java   View Source Code Vote up 5 votes
/**
 * Get the most valuable goods available in one of the player's
 * colonies for the purposes of choosing a threat-to-boycott.  The
 * goods must not currently be boycotted, the player must have
 * traded in it, and the amount to be discarded will not exceed
 * GoodsContainer.CARGO_SIZE.
 *
 * @return A goods object, or null if nothing suitable found.
 */
public Goods getMostValuableGoods() {
    if (!isEuropean()) return null;
    final Market market = getMarket();
    if (market == null) return null;
    final Predicate<Goods> boycottPred = g ->
        getArrears(g.getType()) <= 0 && hasTraded(g.getType());
    final Comparator<Goods> tradedValueComp = Comparator.comparingInt(g ->
        market.getSalePrice(g.getType(),
            Math.min(g.getAmount(), GoodsContainer.CARGO_SIZE)));
    return maximize(flatten(getColonies(),
                            c -> c.getCompactGoodsList().stream()),
                    boycottPred, tradedValueComp);
}
 
Example 11
Project: freecol   File: IndianSettlement.java   View Source Code Vote up 5 votes
/**
 * Chooses a type of goods for some of the natives in a settlement
 * to manufacture.
 * Simple rule: choose the refined goods that is the greatest shortage
 * for which there is a surplus of the raw material.
 *
 * @return A {@code GoodsType} to manufacture, or null if
 *      none suitable.
 */
private GoodsType goodsToMake() {
    final ToIntFunction<GoodsType> deficit = cacheInt(gt ->
        getWantedGoodsAmount(gt) - getGoodsCount(gt));
    final Predicate<GoodsType> goodsPred = gt ->
        gt.isRawMaterial()
            && gt.getOutputType() != null
            && !gt.getOutputType().isBreedable()
            && gt.getOutputType().isStorable()
            && deficit.applyAsInt(gt) < 0
            && deficit.applyAsInt(gt.getOutputType()) > 0;
    final Comparator<GoodsType> comp = Comparator.comparingInt(deficit);
    return maximize(getSpecification().getGoodsTypeList(), goodsPred, comp);
}
 
Example 12
Project: freecol   File: Tile.java   View Source Code Vote up 5 votes
/**
 * Get the best food type to produce here.
 *
 * @return The {@code AbstractGoods} to produce.
 */
public AbstractGoods getBestFoodProduction() {
    final Comparator<AbstractGoods> goodsComp
        = Comparator.comparingInt(ag ->
            getPotentialProduction(ag.getType(), null));
    return maximize(flatten(getType().getAvailableProductionTypes(true),
                            pt -> pt.getOutputs()),
                    AbstractGoods::isFoodType, goodsComp);
}
 
Example 13
Project: ULCRS   File: Scheduler.java   View Source Code Vote up 5 votes
private static Set<Node> search(Node inputNode, int desiredCost) {
    log.info("Searching at desiredCost: " + desiredCost);
    frontier = new PriorityQueue<>(Comparator.comparingInt(Node::getCost));
    explored = new HashSet<>();

    frontier.add(inputNode);

    Set<Node> success = new HashSet<>();

    while (frontier.size() != 0) {
        Node node = frontier.remove();
        explored.add(node);

        int parentCost = generateCost(node);
        log.info("Removing from frontier with cost " + parentCost+ " | remaining nodes on frontier: " + frontier.size());

        List<Node> successors = successors(node);
        for (Node successor : successors) {
            int cost = generateCost(successor);
            if (cost <= desiredCost) {
                success.add(successor);
                if (success.size() >= GENERATE_SCHEDULE_SIZE) {
                    return success;
                }
            }

            if (cost < parentCost && !frontier.contains(successor)) {
                frontier.add(successor);
                log.info("Adding to frontier | parentCost: " + parentCost + " | childCost: " + cost + " | remaining nodes on frontier: " + frontier.size());
            }
        }
    }

    return success.isEmpty() ? null : success;
}
 
Example 14
Project: FreeCol   File: EuropeanAIPlayer.java   View Source Code Vote up 5 votes
/**
 * Gets the best plan for a colony from the tipMap.
 *
 * @param colony The {@code Colony} to check.
 * @return The tile with the best plan for a colony, or null if none found.
 */
public Tile getBestPlanTile(Colony colony) {
    final Comparator<TileImprovementPlan> valueComp
        = Comparator.comparingInt(TileImprovementPlan::getValue);
    final Function<Tile, TileImprovementPlan> tileMapper = t ->
        tipMap.get(t);
    TileImprovementPlan best
        = maximize(map(colony.getOwnedTiles(), tileMapper),
                   isNotNull(), valueComp);
    return (best == null) ? null : best.getTarget();
}
 
Example 15
Project: FreeCol   File: ServerIndianSettlement.java   View Source Code Vote up 5 votes
/**
 * Updates the most hated nation of this settlement.
 * Needs to be public so it can be set by backwards compatibility code
 * in FreeColServer.loadGame.
 *
 * -til: This might change the tile appearance.
 *
 * @return True if the most hated nation changed.
 */
public boolean updateMostHated() {
    final Player old = this.mostHated;
    final Predicate<Player> hatedPred = p -> {
        Tension alarm = getAlarm(p);
        return alarm != null && alarm.getLevel() != Tension.Level.HAPPY;
    };
    final Comparator<Player> mostHatedComp
        = Comparator.comparingInt(p -> getAlarm(p).getValue());
    this.mostHated = maximize(getGame().getLiveEuropeanPlayers(),
                              hatedPred, mostHatedComp);
    return this.mostHated != old;
}
 
Example 16
Project: openjdk-jdk10   File: BasicTest.java   View Source Code Vote up 5 votes
public void testMaxBy() {
    Comparator<People> cmp = Comparator.comparing(People::getFirstName);
    // lesser
    assertSame(maxBy(cmp).apply(people[0], people[1]), people[1]);
    // euqal
    cmp = Comparator.comparing(People::getLastName);
    assertSame(maxBy(cmp).apply(people[0], people[1]), people[0]);
    // greater
    cmp = Comparator.comparingInt(People::getAge);
    assertSame(maxBy(cmp).apply(people[0], people[1]), people[0]);
}
 
Example 17
Project: freecol   File: Player.java   View Source Code Vote up 4 votes
/**
 * Gets the port closest to Europe owned by this player.
 *
 * @return This players closest port.
 */
public Settlement getClosestPortForEurope() {
    final Comparator<Settlement> comp
        = Comparator.comparingInt(Settlement::getHighSeasCount);
    return minimize(getSettlements(), comp);
}
 
Example 18
Project: Apriori   File: TieBreaker.java   View Source Code Vote up 2 votes
/**
 * Adds an additional criteria to the current tie-breaking strategy, which prefers large
 * item sets over small ones. I.e., if an item set contains more items than its counterpart,
 * it is sorted before the other one.
 *
 * @return The tie-breaking strategy, including the added criteria, as an instance of the
 * class {@link ItemSetTieBreaker}. The tie breaking-strategy may not be null
 */
@NotNull
public final ItemSetTieBreaker preferLarge() {
    return new ItemSetTieBreaker(this, Comparator.comparingInt(ItemSet::size));
}
 
Example 19
Project: FreeCol   File: CollectionUtils.java   View Source Code Vote up 2 votes
/**
 * Helper to create a caching comparator.
 *
 * @param <T> The argument type to be converted to int.
 * @param f The integer valued function to use in comparison.
 * @return A caching {@code Comparator}.
 */
public static <T> Comparator<T> cachingIntComparator(Function<T, Integer> f) {
    return Comparator.comparingInt(cacheInt(f));
}
 
Example 20
Project: freecol   File: CollectionUtils.java   View Source Code Vote up 2 votes
/**
 * Helper to create a caching comparator.
 *
 * @param <T> The argument type to be converted to int.
 * @param f The integer valued function to use in comparison.
 * @return A caching {@code Comparator}.
 */
public static <T> Comparator<T> cachingIntComparator(Function<T, Integer> f) {
    return Comparator.comparingInt(cacheInt(f));
}