Example usage for java.lang String compareTo

List of usage examples for java.lang String compareTo

Introduction

In this page you can find the example usage for java.lang String compareTo.

Prototype

public int compareTo(String anotherString) 

Source Link

Document

Compares two strings lexicographically.

Usage

From source file:adalid.commons.util.ObjUtils.java

public static Integer compare(Object x, Object y) {
    if (x == null || y == null) {
        return null;
    }//from ww  w. j ava2s  . com
    if (x instanceof Boolean && y instanceof Boolean) {
        Boolean bx = (Boolean) x;
        Boolean by = (Boolean) y;
        return bx.compareTo(by);
    }
    if (x instanceof String && y instanceof String) {
        String sx = (String) x;
        String sy = (String) y;
        return sx.compareTo(sy);
    }
    if (x instanceof Number && y instanceof Number) {
        BigDecimal nx = NumUtils.numberToBigDecimal(x);
        BigDecimal ny = NumUtils.numberToBigDecimal(y);
        return nx.compareTo(ny);
    }
    if (x instanceof java.util.Date && y instanceof java.util.Date) {
        java.util.Date dx = (java.util.Date) x;
        java.util.Date dy = (java.util.Date) y;
        return dx.compareTo(dy);
    }
    if (x instanceof String || y instanceof String) {
        String sx = toString(x);
        String sy = toString(y);
        if (sx != null && sy != null) {
            return sx.compareTo(sy);
        }
    }
    return null;
}

From source file:me.doshou.admin.maintain.editor.web.controller.utils.OnlineEditorUtils.java

public static void sort(final List<Map<Object, Object>> files, final Sort sort) {

    Collections.sort(files, new Comparator<Map<Object, Object>>() {
        @Override/*  w  ww  . j a va2 s.com*/
        public int compare(Map<Object, Object> o1, Map<Object, Object> o2) {
            if (sort == null) {
                return 0;
            }
            Sort.Order nameOrder = sort.getOrderFor("name");
            if (nameOrder != null) {
                String n1 = (String) o1.get("name");
                String n2 = (String) o2.get("name");
                Boolean n1IsDirecoty = (Boolean) o1.get("isDirectory");
                Boolean n2IsDirecoty = (Boolean) o2.get("isDirectory");

                if (n1IsDirecoty.equals(Boolean.TRUE) && n2IsDirecoty.equals(Boolean.FALSE)) {
                    return -1;
                } else if (n1IsDirecoty.equals(Boolean.FALSE) && n2IsDirecoty.equals(Boolean.TRUE)) {
                    return 1;
                }

                if (nameOrder.getDirection() == Sort.Direction.ASC) {
                    return n1.compareTo(n2);
                } else {
                    return -n1.compareTo(n2);
                }
            }

            Sort.Order lastModifiedOrder = sort.getOrderFor("lastModified");
            if (lastModifiedOrder != null) {
                Long l1 = (Long) o1.get("lastModifiedForLong");
                Long l2 = (Long) o2.get("lastModifiedForLong");
                if (lastModifiedOrder.getDirection() == Sort.Direction.ASC) {
                    return l1.compareTo(l2);
                } else {
                    return -l1.compareTo(l2);
                }
            }

            Sort.Order sizeOrder = sort.getOrderFor("size");
            if (sizeOrder != null) {
                Long s1 = (Long) o1.get("size");
                Long s2 = (Long) o2.get("size");
                if (sizeOrder.getDirection() == Sort.Direction.ASC) {
                    return s1.compareTo(s2);
                } else {
                    return -s1.compareTo(s2);
                }
            }

            return 0;
        }
    });

}

From source file:com.egt.core.util.STP.java

public static boolean esObjetoEnRango(Object objeto, Object minimo, Object maximo) {
    boolean es = true;
    EnumTipoDatoPar tipo;/*from   w ww. j  a v  a2  s  . c  om*/
    if (objeto == null) {
        return false;
    } else if (objeto instanceof String) {
        tipo = EnumTipoDatoPar.ALFANUMERICO;
    } else if (objeto instanceof BigDecimal) {
        tipo = EnumTipoDatoPar.NUMERICO;
    } else if (objeto instanceof Timestamp) {
        tipo = EnumTipoDatoPar.FECHA_HORA;
    } else if (objeto instanceof Integer) {
        tipo = EnumTipoDatoPar.ENTERO;
    } else if (objeto instanceof Long) {
        tipo = EnumTipoDatoPar.ENTERO_GRANDE;
    } else if (objeto instanceof BigInteger) {
        tipo = EnumTipoDatoPar.ENTERO_GRANDE;
    } else {
        return false;
    }
    switch (tipo) {
    case ALFANUMERICO:
        String val1 = (String) objeto;
        String min1 = (String) minimo;
        String max1 = (String) maximo;
        if (min1 != null && val1.compareTo(min1) < 0) {
            es = false;
        }
        if (max1 != null && val1.compareTo(max1) > 0) {
            es = false;
        }
        break;
    case NUMERICO:
        BigDecimal val2 = (BigDecimal) objeto;
        BigDecimal min2 = (BigDecimal) minimo;
        BigDecimal max2 = (BigDecimal) maximo;
        if (min2 != null && val2.compareTo(min2) < 0) {
            es = false;
        }
        if (max2 != null && val2.compareTo(max2) > 0) {
            es = false;
        }
        break;
    case FECHA_HORA:
        Timestamp val3 = (Timestamp) objeto;
        Timestamp min3 = (Timestamp) minimo;
        Timestamp max3 = (Timestamp) maximo;
        if (min3 != null && val3.compareTo(min3) < 0) {
            es = false;
        }
        if (max3 != null && val3.compareTo(max3) > 0) {
            es = false;
        }
        break;
    case ENTERO:
        Integer val4 = (Integer) objeto;
        Integer min4 = (Integer) minimo;
        Integer max4 = (Integer) maximo;
        if (min4 != null && val4.compareTo(min4) < 0) {
            es = false;
        }
        if (max4 != null && val4.compareTo(max4) > 0) {
            es = false;
        }
        break;
    case ENTERO_GRANDE:
        Long val5 = objeto instanceof BigInteger ? ((BigInteger) objeto).longValue() : (Long) objeto;
        Long min5 = (Long) minimo;
        Long max5 = (Long) maximo;
        if (min5 != null && val5.compareTo(min5) < 0) {
            es = false;
        }
        if (max5 != null && val5.compareTo(max5) > 0) {
            es = false;
        }
        break;
    }
    return es;
}

From source file:it.incipict.tool.profiles.util.ProfilesToolUtils.java

public static List<Survey> parseSurvey(File file) throws ProfilesToolException {
    List<Survey> surveys = new ArrayList<Survey>();

    Iterable<CSVRecord> records;
    try {//from  ww  w. ja  v  a2s.  c o  m
        Reader in = new FileReader(file.getCanonicalPath());
        records = CSVFormat.RFC4180.parse(in);
    } catch (IOException e) {
        throw new ProfilesToolException("error while reading files.", e);
    }

    // loop all surveys in CSV line by line
    // note: a single CSV can contain more surveys
    for (CSVRecord record : records) {
        int line = (int) record.getRecordNumber();
        // skip the first line because it simply contains the headers
        if (line > 1) {
            Survey survey = new Survey();
            List<String> answers = new ArrayList<String>();
            List<String> textualAnswers = new ArrayList<String>();
            // in the Survey model we can define a "RECORD OFFSET" by which
            // the parser must start
            for (int i = survey.RECORD_OFFSET; i < record.size(); i++) {
                String r = record.get(i);

                // if the "r" is empty the user has not responded
                // skip to the next answers
                if (r.isEmpty()) {
                    continue;
                }
                // if "r" isn't a numerical value and it is different than
                // ZERO_STRING (Ref. Survey model)
                // Note: the ZERO_STRING is defined in Survey Class. Its
                // value is Zero.
                if ((!r.matches("\\d*") && r.compareTo(survey.ZERO_STRING) != 0)) {
                    // Otherwise the answer is added to a list of Strings.
                    // this list will appended in queue. (*)
                    String[] str = r.split(";");
                    for (String s : str) {
                        textualAnswers.add("\"" + s + "\"");
                    }
                }
                // if "r" is a numeric value, simply add it in the answers
                // list.
                if (r.compareTo(survey.ZERO_STRING) == 0) {
                    answers.add("0");
                }
                if (r.matches("\\d*")) {
                    answers.add(r);
                }
            }
            // add the textual answers in queue (*)
            answers.addAll(textualAnswers);

            String fname = file.getName();
            survey.setProfile(fname.substring(0, fname.lastIndexOf('.')));
            survey.setAnswers(answers);
            surveys.add(survey);
        }
    }
    return (surveys != null) ? surveys : null;
}

From source file:net.objectlab.kit.util.StringUtil.java

/**
 * Handle null./*  ww  w  .  j  a  va2 s .  co  m*/
 */
public static int compareTo(final String s1, final String s2) {
    int ret = -2;
    if (s1 == null && s2 == null) {
        ret = 0;
    } else if (s1 != null && s2 == null) {
        ret = 1;
    } else if (s1 == null && s2 != null) {
        ret = -1;
    }
    return ret == -2 ? s1 != null ? s1.compareTo(s2) : -1 : ret;
}

From source file:client.QueryLastFm.java

License:asdf

public static boolean isAlreadyInserted(String id1, String id2) // also inserts into hashMap if not inserted
{
    boolean isPresent = false;
    if (!isMapCreated) {
        mbidMap = new HashMap<String, String>();
        isMapCreated = true;/*from w ww .ja v  a2  s.c o m*/
    }
    String key = "", value = "";

    // id1 = "2527625b-0752-48f3-95fd-c3f216686db8";
    // id2 = "35143c2f-0484-44e2-bf27-7baa7ca5e135";

    // mbidMap.put(id1+id2, value);
    // System.out.println(mbidMap.containsKey(id1 + id2));
    // return false;
    if (id1.compareTo(id2) < 0) {
        // System.out.println("Expected!!");
        // key = id1 + id2;
        if (mbidMap.containsKey(id1 + id2))
            return true;
        mbidMap.put(id1 + id2, value);
        // value = id2;
    } else if (id1.compareTo(id2) > 0) {
        // System.out.println("Un-Expected!!");
        // key = id2 + id1;
        if (mbidMap.containsKey(id2 + id1))
            return true;
        mbidMap.put(id2 + id1, value);
        // value = id1;
    } else // both keys are equal : No need to insert. Just return true
    {
        // System.out.println("Equal!!");
        return true;
    }
    return isPresent;
}

From source file:com.surfs.storage.web.utils.Stringutils.java

public static String compareReturnBerfore(String baseDate, String strDate) {
    SimpleDateFormat sdf_us = new SimpleDateFormat("EEE MMM dd HH:mm yyyy", Locale.US);
    SimpleDateFormat sdf_cn = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    if (StringUtils.isBlank(baseDate)) {
        if (StringUtils.isBlank(strDate)) {
            return null;
        } else {//from w ww. j av a 2s .  co  m
            try {
                Date date = sdf_us.parse(strDate);
                return sdf_cn.format(date);
            } catch (ParseException e) {
                e.printStackTrace();
                return null;
            }
        }
    }

    try {
        /*String date_us1 = sdf_cn.format(sdf_us.parse(strDate1));*/
        String date_us2 = sdf_cn.format(sdf_us.parse(strDate));
        if (baseDate.compareTo(date_us2) <= 0)
            return baseDate;
        else if (baseDate.compareTo(date_us2) > 0)
            return date_us2;
    } catch (ParseException e) {
        e.printStackTrace();
        return null;
    }
    return strDate;
}

From source file:com.google.gwt.core.ext.typeinfo.TypeOracle.java

/**
 * Convenience method to sort fields in a consistent way. Note that the order
 * is subject to change and is intended to generate an "aesthetically
 * pleasing" order rather than a computationally reliable order.
 *//*w w  w  .  j  av a  2 s. co m*/
public static void sort(JField[] fields) {
    Arrays.sort(fields, new Comparator<JField>() {
        public int compare(JField f1, JField f2) {
            String name1 = f1.getName();
            String name2 = f2.getName();
            return name1.compareTo(name2);
        }
    });
}

From source file:com.google.gwt.core.ext.typeinfo.TypeOracle.java

/**
 * Convenience method to sort methods in a consistent way. Note that the order
 * is subject to change and is intended to generate an "aesthetically
 * pleasing" order rather than a computationally reliable order.
 *//*from w ww  .j  a v a  2 s  .c o  m*/
public static void sort(JMethod[] methods) {
    Arrays.sort(methods, new Comparator<JMethod>() {
        public int compare(JMethod m1, JMethod m2) {
            String name1 = m1.getName();
            String name2 = m2.getName();
            return name1.compareTo(name2);
        }
    });
}

From source file:com.t3.macro.api.functions.input.InputFunctions.java

/**
 * <pre>/*from   ww  w  .j  av a  2 s  .  co m*/
 * <span style="font-family:sans-serif;">The input() function prompts the user to input several variable values at once.
 * 
 * Each of the string parameters has the following format:
 *     "varname|value|prompt|inputType|options"
 * 
 * Only the first section is required.
 *     varname   - the variable name to be assigned
 *     value     - sets the initial contents of the input field
 *     prompt    - UI text shown for the variable
 *     inputType - specifies the type of input field
 *     options   - a string of the form "opt1=val1; opt2=val2; ..."
 * 
 * The inputType field can be any of the following (defaults to TEXT):
 *     TEXT  - A text field.
 *             "value" sets the initial contents.
 *             The return value is the string in the text field.
 *             Option: WIDTH=nnn sets the width of the text field (default 16).
 *     LIST  - An uneditable combo box.
 *             "value" populates the list, and has the form "item1,item2,item3..." (trailing empty strings are dropped)
 *             The return value is the numeric index of the selected item.
 *             Option: SELECT=nnn sets the initial selection (default 0).
 *             Option: VALUE=STRING returns the string contents of the selected item (default NUMBER).
 *             Option: TEXT=FALSE suppresses the text of the list item (default TRUE).
 *             Option: ICON=TRUE causes icon asset URLs to be extracted from the "value" and displayed (default FALSE).
 *             Option: ICONSIZE=nnn sets the size of the icons (default 50).
 *     CHECK - A checkbox.
 *             "value" sets the initial state of the box (anything but "" or "0" checks the box)
 *             The return value is 0 or 1.
 *             No options.
 *     RADIO - A group of radio buttons.
 *             "value" is a list "name1, name2, name3, ..." which sets the labels of the buttons.
 *             The return value is the index of the selected item.
 *             Option: SELECT=nnn sets the initial selection (default 0).
 *             Option: ORIENT=H causes the radio buttons to be laid out on one line (default V).
 *             Option: VALUE=STRING causes the return value to be the string of the selected item (default NUMBER).
 *     LABEL - A label.
 *             The "varname" is ignored and no value is assigned to it.
 *             Option: TEXT=FALSE, ICON=TRUE, ICONSIZE=nnn, as in the LIST type.
 *     PROPS - A sub-panel with multiple text boxes.
 *             "value" contains a StrProp of the form "key1=val1; key2=val2; ..."
 *             One text box is created for each key, populated with the matching value.
 *             Option: SETVARS=SUFFIXED causes variable assignment to each key name, with appended "_" (default NONE).
 *             Option: SETVARS=UNSUFFIXED causes variable assignment to each key name.
 *     TAB   - A tabbed dialog tab is created.  Subsequent variables are contained in the tab.
 *             Option: SELECT=TRUE causes this tab to be shown at start (default SELECT=FALSE).
 * 
 *  All inputTypes except TAB accept the option SPAN=TRUE, which causes the prompt to be hidden and the input
 *  control to span both columns of the dialog layout (default FALSE).
 * </span>
 * </pre>
 * @param parameters a list of strings containing information as described above
 * @return a HashMap with the returned values or null if the user clicked on cancel
 * @author knizia.fan
 * @throws MacroException 
 */
public static Map<String, String> input(TokenView token, String... parameters) throws MacroException {
    // Extract the list of specifier strings from the parameters
    // "name | value | prompt | inputType | options"
    List<String> varStrings = new ArrayList<String>();
    for (Object param : parameters) {
        String paramStr = (String) param;
        if (StringUtils.isEmpty(paramStr)) {
            continue;
        }
        // Multiple vars can be packed into a string, separated by "##"
        for (String varString : StringUtils.splitByWholeSeparator(paramStr, "##")) {
            if (StringUtils.isEmpty(paramStr)) {
                continue;
            }
            varStrings.add(varString);
        }
    }

    // Create VarSpec objects from each variable's specifier string
    List<VarSpec> varSpecs = new ArrayList<VarSpec>();
    for (String specifier : varStrings) {
        VarSpec vs;
        try {
            vs = new VarSpec(specifier);
        } catch (VarSpec.SpecifierException se) {
            throw new MacroException(se);
        } catch (InputType.OptionException oe) {
            throw new MacroException(I18N.getText("macro.function.input.invalidOptionType", oe.key, oe.value,
                    oe.type, specifier));
        }
        varSpecs.add(vs);
    }

    // Check if any variables were defined
    if (varSpecs.isEmpty())
        return Collections.emptyMap(); // No work to do, so treat it as a successful invocation.

    // UI step 1 - First, see if a token is given

    String dialogTitle = "Input Values";
    if (token != null) {
        String name = token.getName(), gm_name = token.getGMName();
        boolean isGM = TabletopTool.getPlayer().isGM();
        String extra = "";

        if (isGM && gm_name != null && gm_name.compareTo("") != 0)
            extra = " for " + gm_name;
        else if (name != null && name.compareTo("") != 0)
            extra = " for " + name;

        dialogTitle = dialogTitle + extra;
    }

    // UI step 2 - build the panel with the input fields
    InputPanel ip = new InputPanel(varSpecs);

    // Calculate the height
    // TODO: remove this workaround
    int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
    int maxHeight = screenHeight * 3 / 4;
    Dimension ipPreferredDim = ip.getPreferredSize();
    if (maxHeight < ipPreferredDim.height) {
        ip.modifyMaxHeightBy(maxHeight - ipPreferredDim.height);
    }

    // UI step 3 - show the dialog
    JOptionPane jop = new JOptionPane(ip, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
    JDialog dlg = jop.createDialog(TabletopTool.getFrame(), dialogTitle);

    // Set up callbacks needed for desired runtime behavior
    dlg.addComponentListener(new FixupComponentAdapter(ip));

    dlg.setVisible(true);
    int dlgResult = JOptionPane.CLOSED_OPTION;
    try {
        dlgResult = (Integer) jop.getValue();
    } catch (NullPointerException npe) {
    }
    dlg.dispose();

    if (dlgResult == JOptionPane.CANCEL_OPTION || dlgResult == JOptionPane.CLOSED_OPTION)
        return null;

    HashMap<String, String> results = new HashMap<String, String>();

    // Finally, assign values from the dialog box to the variables
    for (ColumnPanel cp : ip.columnPanels) {
        List<VarSpec> panelVars = cp.varSpecs;
        List<JComponent> panelControls = cp.inputFields;
        int numPanelVars = panelVars.size();
        StringBuilder allAssignments = new StringBuilder(); // holds all values assigned in this tab

        for (int varCount = 0; varCount < numPanelVars; varCount++) {
            VarSpec vs = panelVars.get(varCount);
            JComponent comp = panelControls.get(varCount);
            String newValue = null;
            switch (vs.inputType) {
            case TEXT: {
                newValue = ((JTextField) comp).getText();
                break;
            }
            case LIST: {
                Integer index = ((JComboBox) comp).getSelectedIndex();
                if (vs.optionValues.optionEquals("VALUE", "STRING")) {
                    newValue = vs.valueList.get(index);
                } else { // default is "NUMBER"
                    newValue = index.toString();
                }
                break;
            }
            case CHECK: {
                Integer value = ((JCheckBox) comp).isSelected() ? 1 : 0;
                newValue = value.toString();
                break;
            }
            case RADIO: {
                // This code assumes that the Box container returns components
                // in the same order that they were added.
                Component[] comps = ((Box) comp).getComponents();
                int componentCount = 0;
                Integer index = 0;
                for (Component c : comps) {
                    if (c instanceof JRadioButton) {
                        JRadioButton radio = (JRadioButton) c;
                        if (radio.isSelected())
                            index = componentCount;
                    }
                    componentCount++;
                }
                if (vs.optionValues.optionEquals("VALUE", "STRING")) {
                    newValue = vs.valueList.get(index);
                } else { // default is "NUMBER"
                    newValue = index.toString();
                }
                break;
            }
            case LABEL: {
                newValue = null;
                // The variable name is ignored and not set.
                break;
            }
            case PROPS: {
                // Read out and assign all the subvariables.
                // The overall return value is a property string (as in StrPropFunctions.java) with all the new settings.
                Component[] comps = ((JPanel) comp).getComponents();
                StringBuilder sb = new StringBuilder();
                int setVars = 0; // "NONE", no assignments made
                if (vs.optionValues.optionEquals("SETVARS", "SUFFIXED"))
                    setVars = 1;
                if (vs.optionValues.optionEquals("SETVARS", "UNSUFFIXED"))
                    setVars = 2;
                if (vs.optionValues.optionEquals("SETVARS", "TRUE"))
                    setVars = 2; // for backward compatibility
                for (int compCount = 0; compCount < comps.length; compCount += 2) {
                    String key = ((JLabel) comps[compCount]).getText().split("\\:")[0]; // strip trailing colon
                    String value = ((JTextField) comps[compCount + 1]).getText();
                    sb.append(key);
                    sb.append("=");
                    sb.append(value);
                    sb.append(" ; ");
                    switch (setVars) {
                    case 0:
                        // Do nothing
                        break;
                    case 1:
                        results.put(key + "_", value);
                        break;
                    case 2:
                        results.put(key, value);
                        break;
                    }
                }
                newValue = sb.toString();
                break;
            }
            default:
                // should never happen
                newValue = null;
                break;
            }
            // Set the variable to the value we got from the dialog box.
            if (newValue != null) {
                results.put(vs.name, newValue.trim());
                allAssignments.append(vs.name + "=" + newValue.trim() + " ## ");
            }
        }
        if (cp.tabVarSpec != null) {
            results.put(cp.tabVarSpec.name, allAssignments.toString());
        }
    }

    return results; // success

    // for debugging:
    //return debugOutput(varSpecs);
}