Example usage for java.util Collections max

List of usage examples for java.util Collections max

Introduction

In this page you can find the example usage for java.util Collections max.

Prototype

public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) 

Source Link

Document

Returns the maximum element of the given collection, according to the natural ordering of its elements.

Usage

From source file:au.org.ala.delta.key.Key.java

private void printTabularKey(TabularKey key, PrintFile printFile) {
    ItemFormatter itemFormatter = new ItemFormatter(false, CommentStrippingMode.STRIP_ALL,
            AngleBracketHandlingMode.REMOVE, true, false, false);

    // Do a first pass of the data structure to get the counts for the
    // number of times a taxon appears in the key, and to work out how wide
    // the cells need to be
    Map<Item, Integer> itemOccurrences = new HashMap<Item, Integer>();
    int cellWidth = 0;

    for (TabularKeyRow row : key.getRows()) {
        Item it = row.getItem();// w  w w  .j  a v a2s .  co  m

        if (itemOccurrences.containsKey(it)) {
            int currentItemCount = itemOccurrences.get(it);
            itemOccurrences.put(it, currentItemCount + 1);
        } else {
            itemOccurrences.put(it, 1);
        }

        // If TRUNCATE TABULAR KEY AT directive has been used, only
        // traverse up to the relevant column.
        int columnLimit = row.getNumberOfColumns();
        if (_context.getTruncateTabularKeyAtColumnNumber() != -1) {
            columnLimit = _context.getTruncateTabularKeyAtColumnNumber();
        }

        for (int i = 0; i < columnLimit; i++) {
            int columnNumber = i + 1;

            for (MultiStateAttribute attr : row.getAllAttributesForColumn(columnNumber)) {
                int characterNumber = attr.getCharacter().getCharacterId();
                int numberOfDigits = Integer.toString(characterNumber).length();

                // Cell width needs to be at least as wide as the number of
                // digits, plus one extra character for the state value
                // associated with the attribute
                if (cellWidth < numberOfDigits + 1) {
                    cellWidth = numberOfDigits + 1;
                }
            }
        }
    }

    // Highest number of item occurrences in the key
    int maxItemOccurrences = Collections.max(itemOccurrences.values());

    // Determine the maximum allowable length for a formatted taxon name in
    // the tabulated key. This will be the length
    // of the name cell, less the length of the largest number of item
    // occurrences (these are printed right-justified) in the cell, with a
    // space between the name and the item occurrence count.
    int maxFormattedItemNameLength = TABULATED_KEY_NAME_CELL_WIDTH
            - Integer.toString(maxItemOccurrences).length() - 1;

    StringBuilder builder = new StringBuilder();

    // Second pass - output the key
    for (int i = 0; i < key.getNumberOfRows(); i++) {
        TabularKeyRow row = key.getRowAt(i);
        Item it = row.getItem();

        List<MultiStateAttribute> rowAttributes;
        List<MultiStateAttribute> previousRowAttributes = null;

        // If TRUNCATE TABULAR KEY AT directive has been used, only
        // traverse up to the relevant column.
        int columnLimit = row.getNumberOfColumns();

        if (_context.getTruncateTabularKeyAtColumnNumber() == -1) {
            rowAttributes = row.getAllAttributes();
            if (i > 0) {
                previousRowAttributes = key.getRowAt(i - 1).getAllAttributes();
            }
        } else {
            columnLimit = _context.getTruncateTabularKeyAtColumnNumber();
            rowAttributes = row.getAllCharacterValuesUpToColumn(columnLimit);
            if (i > 0) {
                previousRowAttributes = key.getRowAt(i - 1).getAllCharacterValuesUpToColumn(columnLimit);
            }
        }

        // Output the dividing line between the previous row and the current
        // row
        builder.append("+---------------------------+");

        for (int j = 0; j < rowAttributes.size(); j++) {
            Attribute currentRowAttribute = rowAttributes.get(j);

            if (previousRowAttributes != null && previousRowAttributes.size() >= j + 1) {
                Attribute previousRowAttribute = previousRowAttributes.get(j);
                if (currentRowAttribute.equals(previousRowAttribute)) {
                    builder.append(StringUtils.repeat(" ", cellWidth));
                    builder.append("|");
                } else {
                    builder.append(StringUtils.repeat("-", cellWidth));
                    builder.append("+");
                }

            } else {
                builder.append(StringUtils.repeat("-", cellWidth));
                builder.append("+");
            }
        }

        if (previousRowAttributes != null) {
            int diffPrevRowAttributes = previousRowAttributes.size() - rowAttributes.size();
            for (int k = 0; k < diffPrevRowAttributes; k++) {
                builder.append(StringUtils.repeat("-", cellWidth));
                builder.append("+");
            }
        }

        builder.append("\n");

        // Output the item name and the number of occurences of the item in
        // the key, if it appears more than once
        builder.append("|");
        String formattedItemName = itemFormatter.formatItemDescription(it);
        formattedItemName = StringUtils.substring(formattedItemName, 0, maxFormattedItemNameLength);
        builder.append(formattedItemName);

        int numItemOccurrences = itemOccurrences.get(it);

        if (numItemOccurrences > 1) {
            builder.append(StringUtils.repeat(" ", TABULATED_KEY_NAME_CELL_WIDTH - formattedItemName.length()
                    - Integer.toString(numItemOccurrences).length()));
            builder.append(numItemOccurrences);
        } else {
            builder.append(StringUtils.repeat(" ", TABULATED_KEY_NAME_CELL_WIDTH - formattedItemName.length()));
        }

        builder.append("|");

        // Output the values character values used in the. Include values
        // for confirmatory characters if they are present
        for (int j = 0; j < columnLimit; j++) {
            int columnNumber = j + 1;
            List<MultiStateAttribute> cellCharacterValues = row.getAllAttributesForColumn(columnNumber);
            for (int k = 0; k < cellCharacterValues.size(); k++) {
                MultiStateAttribute cellCharacterValue = cellCharacterValues.get(k);
                int characterId = cellCharacterValue.getCharacter().getCharacterId();

                // Insert spaces to pad out the cell if the character id +
                // state
                // value are not as wide as the cell width
                builder.append(
                        StringUtils.repeat(" ", cellWidth - (Integer.toString(characterId).length() + 1)));

                builder.append(characterId);

                // Only 1 state will be ever set - the key generation
                // algorithm
                // only sets
                // Individual states for characters
                int stateNumber = cellCharacterValue.getPresentStates().iterator().next();
                // Convert state numbers to "A", "B", "C" etc
                builder.append((char) (64 + stateNumber));

                if (cellCharacterValues.size() > 1 && k < cellCharacterValues.size() - 1) {
                    builder.append(" ");
                }
            }

            builder.append("|");
        }

        builder.append("\n");

        // If this is the last row, need to print the bottom edge of the
        // table
        if (i == key.getNumberOfRows() - 1) {
            builder.append("+---------------------------+");
            for (int l = 0; l < rowAttributes.size(); l++) {
                builder.append(StringUtils.repeat("-", cellWidth));
                builder.append("+");
            }
        }
    }

    printPagedTabularKey(builder.toString(), cellWidth, printFile);
}

From source file:webServices.RestServiceImpl.java

public String wktToExtent(String wkt) {
    Vector<Double> allX = new Vector<Double>();
    Vector<Double> allY = new Vector<Double>();

    wkt = wkt.substring(wkt.indexOf("((") + 2, wkt.indexOf("))"));

    String[] parse = wkt.split(", ");

    try {/*www .jav  a 2  s.  c o m*/
        for (int i = 0; i < parse.length; i++) {
            String[] getXY = parse[i].split(" ");
            allX.add(Double.parseDouble(getXY[0]));
            allY.add(Double.parseDouble(getXY[1]));
        }

        return "[" + Collections.min(allX).toString() + ", " + Collections.min(allY).toString() + ", "
                + Collections.max(allX).toString() + ", " + Collections.max(allY).toString() + "]";
    } catch (NumberFormatException e) {
        return "[-180.0, -90.0, 180.0, 90.0]";
    }
}

From source file:carskit.data.processor.DataDAO.java

public double getRatingMax() {
    if (MaxRate == -1)
        MaxRate = Collections.max(getRatingScale());
    return MaxRate;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.tsv.WebannoTsv3Writer.java

/**
 * Annotations of same type those: <br>
 * 1) crosses multiple sentences AND <br>
 * 2) repeated on the same unit (even if different value) <br>
 * Will be referenced by a number so that re-importing or processing outside
 * WebAnno can be easily distinguish same sets of annotations. This is much
 * Meaningful for relation/slot and chain annotations. Reference numbers are incremental 
 * /* www . jav  a  2  s  .co m*/
 * @param type
 *            The annotation type
 * @param fs
 *            the annotation
 * @param unit
 *            the annotation element (Token or sub-tokens)
 * @return the reference number to be attached on this annotation value
 */
private int getRefId(Type type, AnnotationFS fs, AnnotationUnit unit) {

    // first time
    if (annotaionRefPerType.get(type) == null) {

        Map<FeatureStructure, Integer> annoRefs = new HashMap<>();
        annoRefs.put(fs, 1);
        annotaionRefPerType.put(type, annoRefs);

        multiAnnosPerUnit.putIfAbsent(type, new HashMap<>());
        Map<FeatureStructure, Integer> multiAnooRefs = new HashMap<>();
        multiAnooRefs.put(fs, 1);
        multiAnnosPerUnit.get(type).put(unit, multiAnooRefs);
        return 1;
    } else {

        // This is a multiple token annotation, re-USE reference id
        if (annotaionRefPerType.get(type).get(fs) != null) {
            return annotaionRefPerType.get(type).get(fs);
        }

        Map<FeatureStructure, Integer> annoRefs = annotaionRefPerType.get(type);
        int max = Collections.max(annoRefs.values()); // the last reference number so far.
        annoRefs.put(fs, max + 1);
        annotaionRefPerType.put(type, annoRefs);

        /*            Map<Integer, FeatureStructure> refsAnnos = refAnnotaionperType.get(type);
                    refsAnnos.put(max + 1, fs);
                    refAnnotaionperType.put(type, refsAnnos);*/

        int ref = annotaionRefPerType.get(type).get(fs);
        Map<FeatureStructure, Integer> multiAnooRefs = multiAnnosPerUnit.get(type).get(unit);
        if (multiAnooRefs == null) {
            multiAnooRefs = new HashMap<>();
            multiAnooRefs.put(fs, ref);
            multiAnnosPerUnit.get(type).put(unit, multiAnooRefs);
            return ref;
        }
        // this is for sure a stacked annotation
        else {
            multiAnooRefs.put(fs, ref);
            multiAnnosPerUnit.get(type).put(unit, multiAnooRefs);
            return ref;
        }
    }
}

From source file:org.mifos.customers.business.CustomerBO.java

/**
 * Returns the amount which this customer
 *
 **//*from w w  w  .  j  a v a2  s.  c o m*/
public Money getMaxLoanAmount(final LoanOfferingBO loanOffering) {
    ArrayList<Money> loanAmounts = new ArrayList<Money>();
    Set<AccountBO> accounts = getAccounts();
    for (AccountBO accountBO : accounts) {
        // If account not in loan obligations met, continue to next loan
        // account
        if (!accountBO.isInState(AccountState.LOAN_CLOSED_OBLIGATIONS_MET)) {
            continue;
        }

        if (accountBO.isLoanAccount() && ((LoanBO) accountBO).isOfProductOffering(loanOffering)) {
            loanAmounts.add(((LoanBO) accountBO).getLoanAmount());
        }
    }
    if (loanAmounts.isEmpty()) {
        loanAmounts.add(zero());
    }
    return Collections.max(loanAmounts);
}

From source file:org.zkoss.ganttz.data.GanttDiagramGraph.java

private GanttDate getBiggestEndDateFromChildrenFor(V container) {
    return Collections.max(getChildrenDates(container, Point.END));
}

From source file:org.mifos.test.acceptance.questionnaire.QuestionGroupTest.java

private Integer latestInstanceId(Map<Integer, QuestionGroup> questionGroups) {
    Set<Integer> keys = questionGroups.keySet();
    return Collections.max(keys);
}

From source file:qmul.align.AlignmentTester.java

/**
 * Normalise a data array depending on the normalisation setting
 * /*from   w  w  w.j  a  va  2  s  .  c om*/
 * @param data
 */
private void normalise(List<Double> data) {
    double norm = 1.0;
    if (normalisation == NORM_MAX) {
        norm = Collections.max(data);
    } else if (normalisation == NORM_MEAN) {
        double sum = 0.0;
        for (Double datum : data) {
            sum += datum;
        }
        norm = (sum / data.size());
    }
    for (int i = 0; i < data.size(); i++) {
        data.set(i, data.get(i) / norm);
    }
}

From source file:org.libreplan.business.planner.entities.ResourceAllocation.java

private ResourcesPerDay calculateResourcesPerDayFromAssignments(Collection<? extends T> assignments) {
    if (assignments.isEmpty()) {
        return ResourcesPerDay.amount(0);
    }//from w  ww  .j  a  v a2 s . c om

    Map<LocalDate, List<T>> byDay = DayAssignment.byDay(assignments);
    LocalDate min = Collections.min(byDay.keySet());
    LocalDate max = Collections.max(byDay.keySet());
    Iterable<PartialDay> daysToIterate = startFor(min).daysUntil(endFor(max));

    EffortDuration sumTotalEffort = zero();
    EffortDuration sumWorkableEffort = zero();
    final ResourcesPerDay ONE_RESOURCE_PER_DAY = ResourcesPerDay.amount(1);

    for (PartialDay day : daysToIterate) {
        List<T> assignmentsAtDay = avoidNull(byDay.get(day.getDate()), Collections.<T>emptyList());

        EffortDuration incrementWorkable = getAllocationCalendar().asDurationOn(day, ONE_RESOURCE_PER_DAY);
        sumWorkableEffort = sumWorkableEffort.plus(incrementWorkable);

        sumTotalEffort = sumTotalEffort.plus(sumDuration(assignmentsAtDay));
    }
    if (sumWorkableEffort.equals(zero())) {
        return ResourcesPerDay.amount(0);
    }

    return ResourcesPerDay.calculateFrom(sumTotalEffort, sumWorkableEffort);
}

From source file:net.geoprism.dashboard.DashboardMap.java

public Map<String, Integer> calculateLayerIndices() {
    Map<String, Integer> uIndexes = this.getDashboard().getUniversalIndices();

    DashboardLayer[] layers = this.getOrderedLayers();

    int index = Collections.max(uIndexes.values()) + 1;

    Map<String, Integer> indices = new HashMap<String, Integer>();

    for (DashboardLayer layer : layers) {
        if (layer instanceof DashboardReferenceLayer) {
            DashboardReferenceLayer referenceLayer = (DashboardReferenceLayer) layer;

            Integer universalIndex = uIndexes.get(referenceLayer.getUniversal().getId());

            indices.put(layer.getId(), universalIndex);
        } else {//w w w . jav  a 2  s .c  o  m
            indices.put(layer.getId(), index++);
        }
    }

    return indices;
}