Sorting String Value

Hi All,
i have a simple question but don't know how to resolve it
i have some files with name like abc_15-06-09 we need to sort these file based on the time stamp appended at the end of the file, in my example "15-06-09"
i am not sure how can i sort these string value provided i can just take these time stamp from the file using sub-string.i need to sort these file based on the stamp old time stamp will get preference
any help in this regard wil be mcuh appricaited
thnaks in advance,
umesh

umesh_awasthi wrote:
try
Date today;
ArrayList<Date> datetoComp=new ArrayList<Date>();
today = df.parse("12/10/2009/12/34/18");
datetoComp.add(today);
today = df.parse("12/10/2008/12/34/18");
datetoComp.add(today);
today = df.parse("12/10/2009/12/34/18");
datetoComp.add(today);
today = df.parse("11/10/2009/12/34/18");
datetoComp.add(today);
today = df.parse("12/10/2009/12/34/18");
datetoComp.add(today);
System.out.println(datetoComp.size());
Collections.sort(datetoComp);
for (Iterator i = datetoComp.iterator(); i.hasNext();)
          Date currentDate = (Date) i.next();
          System.out.println(currentDate);
} catch (ParseException e)
Result:
Sat Jan 12 00:34:18 IST 2008
Sun Jan 11 00:34:18 IST 2009
Mon Jan 12 00:34:18 IST 2009
Mon Jan 12 00:34:18 IST 2009
Mon Jan 12 00:34:18 IST 2009
not as expectedfirst learn to put your code in [{}{code}] format.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • Sorting string values

    I have strings in a vector with values like "2-name","6-name2"...etc...what i want to do is sort them according to the number in the string.Is there any way we can do that using java api...or do we need to write a program to do that ....
    thanks
    satish

    Write a custom Comparator class, then use it as part of a call to Collection.sort(List list, Comparator c). A Comparator tells Java how to compare two objects. Here is a suggestion:
    public class CustomComparator implements Comparator
    public int compare(Object o1, Object o2)
      String s1 = (String) o1;
      String s2 = (String) o2;
      int pos1 = s1.indexOf('-');
      int pos2 = s2.indexOf('-');
      String value1 = s1.substring(0, pos1);
      String value2 = s2.substring(0, pos2);
      int v1 = Integer.parseInt(value1);
      int v2 = Integer.parsetInt(value2);
      return v2 - v1;
    }

  • Sorting the values in Map

    Hi,
    In my application, i want to use Mapping in the case
    Key -Value
    A - 2
    B - 3
    C - 7
    D - 5
    For that I used HashMap. But I want to sort the values and place in map as from Highest order. For that in google it is suggested to refer SortedMap. But this SortedMap is sorting the Key content only not Value content.
    For sorting the Value's what I have to do under Collection?
    Any idea?

    DHURAI wrote:
    I will explain my concept in detail.
    I am having a String array; a[]={qw,q,as,l,kj,q,q,l}
    From this i am mapping
    key value
    qw 1
    q 3
    as 1
    l 2
    kj 1
    using HashMap.
    From this I want to fetch q whose value is greater. How can I do this?
    Hope this explains better.You still haven't said how often you want to do that. What I explained will work, but it might not be what you want if you often change values.

  • [C] Trying to sort string into reverse order ... Blank. [SOLVED]

    Here are the pre-processors:
    #include <stdio.h>
    #include <string.h>
    Here are the global variables:
    char output[999];
    Here's the function to sort string to reverse order (I THINK THE PROBLEM IS HERE):
    char output[999];
    char *sort_reverse(const char *str)
    int i, j = 0;
    for (i = strlen(str); i > 0; i--)
    output[j] = str[i];
    j++;
    return output;
    And, function int main(void):
    int main(void)
    printf("Reverse of \"Hello\": %s\n", sort_reverse("Hello"));
    return 0;
    The output is:
    Reverse of "Hello":
    Why is that? how can i fix that?
    Last edited by milo64 (2013-03-28 01:45:46)

    Instead of the global char output[999] wich is really big, you could allocate a perfectly sized array with calloc - like this in the sort_reverse function:
    char *output = calloc(strlen(input_string), sizeof(char));
    and in main program:
    char *reversed_string = sort_reverse("Whatever");
    printf("%s\n", reversed_string);
    //Remember to free reversed_string with
    free(reversed_string);
    //Since its allocated in the heap with calloc()
    Try check man-page for calloc, it will zero out the bytes aswell, then you wont have to worry about setting the last element to '\0'.
    NOTE: you have to iterate with "strlen(input_string) - 1" otherwise you will overwrite the needed '\0'
    EDIT:  As strlen excludes the '\0' in original string, then you have to make space for that by adding one to strlen return value so:
    char *output = calloc(strlen(input_string) + 1, sizeof(char));
    Last edited by Boogie (2013-04-05 09:46:12)

  • Error: Find criteria must contain at least one sort field value.

    Hi
    I am getting the followng error in Sort.as when I click on a column in a DataGrid that is bound to a nested property (e.g. parent.name)
    Error: Find criteria must contain at least one sort field value.
    I can see why this is failing.
    In the findItem function of Sort.as the code tests whether there is data in line (456) hasFieldName = values[fieldName] !== undefined. This fails and so an error is raised later in the function by:
         if (fieldsForCompare.length == 0)     {
         message = resourceManager.getString("collections", "findRestriction"); 
              throw new SortError(message);     }
     The code needs to traverse down the object hierarchy to get the field so that error is not thrown .
    The code needs to traverse down the object hierarchy to get the field so that error is not thrown .
    In the case of a non nested property, everything works fine.
    There is lots of discussion about nested properties in DataGrid and there is this jira:
    http://bugs.adobe.com/jira/browse/SDK-9801
    There is talk of using a labelFunction or an itemRenderer and other third party solutions (extensions of DataGridColumn).
    Is this a bug?  is there a workaround using labelFunction or itemRenderer which can stop the error in Sort.as?
    James
    Here is the code of findItem in Sort.as of SDK 3..4.0.9271
    public  
    function findItem(items:Array,values:Object,
    mode:String,
    returnInsertionIndex:Boolean =
    false,compareFunction:Function =
    null):int{
    var compareForFind:Function; 
    var fieldsForCompare:Array; 
    var message:String; 
    if (!items){
    message = resourceManager.getString(
    "collections", "noItems"); 
    throw new SortError(message);}
    else if (items.length == 0){
    return returnInsertionIndex ? 1 : -1;}
    if (compareFunction == null){
    compareForFind =
    this.compareFunction; 
    // configure the search criteria
    if (values && fieldList.length > 0){
    fieldsForCompare = [];
    //build up the fields we can compare, if we skip a field in the
    //middle throw an error. it is ok to not have all the fields
    //though
    var fieldName:String; 
    var hadPreviousFieldName:Boolean = true; 
    for (var i:int = 0; i < fieldList.length; i++){
    fieldName = fieldList[i];
    if (fieldName){
    var hasFieldName:Boolean; 
    try
    hasFieldName = values[fieldName] !==
    undefined;}
    catch(e:Error){
    hasFieldName =
    false;}
    if (hasFieldName){
    if (!hadPreviousFieldName){
    message = resourceManager.getString(
    "collections", "findCondition", [ fieldName ]); 
    throw new SortError(message);}
    else
    fieldsForCompare.push(fieldName);
    else
    hadPreviousFieldName =
    false;}
    else
    //this is ok because sometimes a sortfield might
    //have a custom comparator
    fieldsForCompare.push(
    null);}
    if (fieldsForCompare.length == 0){
    message = resourceManager.getString(
    "collections", "findRestriction"); 
    throw new SortError(message);}
    else
    try
    initSortFields(items[0]);
    catch(initSortError:SortError){
    //oh well, use the default comparators...
    else
    compareForFind = compareFunction;

    I have tried a sortCompareFunction:
    var sort:Sort = new Sort();
    sort.compareFunction = compareFunction;sort.fields = [sortField];
    data.sort = sort;
    data.refresh();
    this makes no difference.
    James

  • Sorting the values of a map.

    I have been stuck on this problem for a while. I have a TreeMap, which can be changed to a HashMap if needed, with a set of keys as Strings and values which are Integers.
    EXAMPLE
    String1, 123
    String2, 333
    String3, 222
    String4, 758
    I need the values sorted in decending order (9-0).
    Thanks in advance for all your help.

    I have been stuck on this problem for a while. I have
    a TreeMap, which can be changed to a HashMap if
    needed, with a set of keys as Strings and values which
    are Integers.You must be the first one who changed a TreeMap into a HashMap and then lived to tell about it. -:)
    Anyway a TreeMap is always sorted on key, not value. To have your dataset sorted on value you must reload into another TreeMap and invert the key/value pairs in the process. The values then become keys in the new TreeMap which means that the former values must be unique for this to work.
    I'm sure there's a simple solution but it's better if you described what you want to accomplish in general terms than to let people struggle with a solution scenario that's probably suboptimal. How do you want to access your objects and why and when do you need them to be sorted.

  • Problem to get max string value

    Hi
    my problem is i don't get correct result when i get max string value from my table. for example, it returns '9' as max value while i have some bigger string values like 73, 80,65, ...
    i found
    some solutions to handle this problem (like converting to char or adding some zero in the begining of my value) but it does not appropriate for my situation because my string value maybe everything (some of my customers can use numbers while some other
    else can use alphabetical+numbers)!.
    can anybody help me ?
    thanks in advance
    http://www.codeproject.com/KB/codegen/DatabaseHelper.aspx

    When I see NVARCHAR(50)(50) I am pretty sure the data was declared by an ACCESS programmer who has no idea what he is doing. Do you really have first
    and last names that need fifty UNICODE characters ?  You will get them!  If you invite garbage data, it will come. The USPS uses VARCHAR(20) for names; this has to do with the size of mailing labels and the fact
    that Latin-1 is required by ISO in ALL languages. 
    lease read the  "Stairway to Data" series and pay attention to last sections on the design of encoding schemes. What you have is useless and dangerous because it has no data integrity.  Tag
    numbers (learn what that means, please) need a regular expression and I like to have a check digit. My first guess, without an specs is that you need something like this:  
    patient _case_nbr CHAR() NOT NULL PRIMARY KEY
     CHECK (patient _case_nbr 
      LIKE '[ ABC][0-9][0-9][0-9][0-9][0-9]')
    Fixed length for the forms and display, characters limtied to the Latin-1 Unicode set, and easy to sort. 
     http://www.sqlservercentral.com/articles/Database+Design/72612/)
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • How to sort alphanumeric values in datagrid numerically

    Hi all,
    I have a datagrid column which contains AlphaNumeric values.Is there a way i can sort these values in a numerical order
    eg:
    having d1,d11,12,13,d2,d3,d4
    d2 should come after d1..
    order should be d1,d2,d3,d4,d11,d12,d13
    Please help me out..if any have any idea..giving below thw code which is sorting as string
    protected function ColumnSortCompare( obj1:Object, obj2:Object ):int
            if ( !obj1 && !obj2 )
                return 0;
            if ( !obj1 )
                return 1;
            if ( !obj2 )
                return -1;
            var obj1Data:String = ComplexColumnData( obj1 ).toString();
            var obj2Data:String = ComplexColumnData( obj2 ).toString();
            if ( obj1Data < obj2Data )
                return -1;
            if ( obj1Data > obj2Data )
                return 1;
            return 0;
    Thanx in advance
    Rajesh

    Hi,
    Thanks for the reply. Please dont mind if the question is simple,as I am new to flex.
    While I am using
    return ObjectUtil.stringCompare(obj1[fieldName], obj2[fieldName]);
    it is throwing error as, undefined property fieldName.
    I am calling as this
    <mx:DataGridColumn headerText=""
                               editable="false"
                               sortCompareFunction="ColumnSortCompare"
                               textAlign="left"
                               dataField="{PORT_NAME}"
                               width="150"/>
    How I can resolve this.Please guide me.
    Thanks,
    Raj

  • Is there a standard map sorted by values

    Tree Map is sorted by keys..Is there standard jdk map sorted by values ?

    You can also use a method similar to the following:
    private static final Collator PL_COLLATOR = Collator.getInstance(new Locale("PL"));
         public static <E> Map<E, String> sortMapByValue(Map<E, String> unordered) {
              Map<E, String> ret = new LinkedHashMap<E, String>();
              Set<Entry<E, String>> sort = new TreeSet<Entry<E, String>>(new Comparator<Entry<E, String>>() {
                   public int compare(Entry<E, String> o1, Entry<E, String> o2) {
                        Entry<E, String> e1 = o1;
                        Entry<E, String> e2 = o2;
                        String s1 = e1.getValue();
                        String s2 = e2.getValue();
                        return PL_COLLATOR.compare(s1.toLowerCase(), s2.toLowerCase());
              sort.addAll(unordered.entrySet());
              for (Iterator<Entry<E, String>> iterator = sort.iterator(); iterator.hasNext();) {
                   Entry<E, String> e = iterator.next();
                   ret.put(e.getKey(), e.getValue());
              return ret;
         }

  • Parameters To Include Null Or Empty String Values

    I have a table that has both Nulls & Empty Strings that I want to use as a Dynamic Parameter.  Even though there is an indication of the Null/Empty String value when the parameter prompt comes up, selecting the value of Null/Empty String results in no records being returned.  I have a formula to display the values in the report (where I substitute "Unknown" for the Null/Empty String values), but I am not able to do a parameter on that formula.
    I guess in general, this is a situation of needing to be able to use a Dynamic Parameter based on a formula field.
    Thanks for any assistance!  
    Edited by: Dragon77 on Apr 2, 2010 9:39 AM

    I'd use a SQL Command as the data source for the list of values. Something like this... (MS SQL Server)
    SELECT DISTINCT
    CASE WHEN t.StringField IS NULL OR  t.StringField LIKE ''
         THEN 'Unknown' ELSE  t.StringField END AS  StringField
    FROM TableName AS t
    ORDER BY  StringField
    Then use a formula like this in the selection criteria.
    IF {?Parameter} = "Unknown"
    THEN (ISNULL ({TableName.StringField}) OR {TableName.StringField} LIKE "")
    ELSE {TableName.StringField} = {?Parameter}
    HTH,
    Jason

  • How to get string value from xml in JSF??

    In JSF How to get string value from xml, .ini and properties file. I want to get string value from xml or text to JSF

    Just use the appropriate API's for that. There are enough API's out which can read/parse/write XML, ini and properties files. E.g. JAXP or DOM4J for xml files, INI4J for ini files and Sun's own java.util.Properties for propertiesfiles.
    JSF supports properties files as message bundle and resource bundle so that you can use them for error messages and/or localization.

  • How to get string value from database table using Visual Studio 2005?

    Hi,
    Im developing plugin in illustrator cs3 using visual studio 2005. I need to get the values eneterd in database. Im able to get the integer values. But while getting string values it is returning empty value.
    Im using the below code to get the values from database table
    bool Table::Get(char* FieldName,int& FieldValue)
        try
            _variant_t  vtValue;
            vtValue = m_Rec->Fields->GetItem(FieldName)->GetValue();
            FieldValue=vtValue.intVal;
        CATCHERRGET
        sprintf(m_ErrStr,"Success");
        return 1;
    Im using the below code to get the values.
    AIErr getProjects()
        char buf[5000];
        int i;   
        std::string  catName;
        ::CoInitialize(NULL);
        Database db;
        Table tbl;
        errno_t err;
        err = fopen(&file,"c:\\DBResult.txt","w");
        fprintf(file, "Before Connection Established\n");
        //MessageBox(NULL,CnnStr,"Connection String",0);
        if(!db.Open(g->username,g->password,CnnStr))
            db.GetErrorErrStr(ErrStr);
            fprintf(file,"Error: %s\n",ErrStr);
        fprintf(file, "After Connection Established\n");
    if(!db.Execute("select ProjectID,ProjectName from projectsample",tbl))
            db.GetErrorErrStr(ErrStr);
            fprintf(file,"Error: %s\n",ErrStr);
        int ProjectID;
        int UserID;
        int ProjectTitle;
        char ProjectName[ProjectNameSize];
        if(!tbl.ISEOF())
            tbl.MoveFirst();
        ProjectArrCnt=0;
        for(i=0;i<128;i++)
            buf[i]='\0';
            int j=0;
        while(!tbl.ISEOF())
            if(tbl.Get("ProjectID",ProjectID))
                fprintf(file,"Project ID: %d ",ProjectID);
                ProjectInfo[ProjectArrCnt].ProjectID = ProjectID;
                sprintf(buf,"%d",ProjectID);
                //MessageBox(NULL, buf,"f ID", 0);
                j++;
            else
                tbl.GetErrorErrStr(ErrStr);
                fprintf(file,"Error: %s\n",ErrStr);
                break;
            //if(tbl.Get("ProjectTitle",ProjectName))
            if(tbl.Get("ProjectName",ProjectName))
                MessageBox(NULL,"Inside","",0);
                fprintf(file,"ProjectTitle: %s\n",ProjectName);
                //catName=CategoryName;
                ProjectInfo[ProjectArrCnt].ProjectName=ProjectName;
                //sprintf(buf,"%s",ProjectName);
                MessageBox(NULL,(LPCSTR)ProjectName,"",0);
            else
                tbl.GetErrorErrStr(ErrStr);
                fprintf(file,"Error: %s\n",ErrStr);
                break;
            ProjectArrCnt++;
            //MessageBox(NULL, "While", "WIN API Test",0);
            tbl.MoveNext();
        //MessageBox(NULL, ProjectInfo[i].ProjectName.c_str(),"f Name", 0);
        ::CoUninitialize();
        //sprintf(buf,"%s",file);
        //MessageBox(NULL,buf,"File",0);
        fprintf(file, "Connection closed\n");
        fclose(file);
        for(i=0;i<ProjectArrCnt;i++)
            sprintf(buf,"%i",ProjectInfo[i].ProjectID);
            //MessageBox(NULL,buf,"Proj ID",0);
            //MessageBox(NULL,ProjectInfo[i].ProjectName.c_str(),"Project Name",0);
        return 0;
    In the above code im geeting project D which is an integer value. But not able to get the project name.
    Please some one guide me.

    As I said in the other thread, this really isn't the place to ask questions about a database API unrelated to the Illustrator SDK. You're far more like to find people familliar with your problem on a forum that is dedicated to answering those kinds of questions instead.

  • Getting string values from DB query

    I am using the following code:
    <%@ page import="java.sql.*" %>
    <%
        String userName = request.getParameter("usernameField");
        String password = request.getParameter("passwordField");
        String connectionURL = "jdbc:mysql://localhost:3306/babbemployees?user=DBUser;password=MyPassword";
        Connection connection = null;
        Statement statement = null;
        ResultSet rs = null;
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        connection = DriverManager.getConnection  (connectionURL, "DBUser", "MyPassword");
        statement = connection.createStatement();
        String queryString = "SELECT * FROM tbemployees where userID='"+userName+"'";
        rs = statement.executeQuery(queryString);   
        String isAuthenticated;
        if (userName == rs.getString("userID") && password == rs.getString("password")[0])
            isAuthenticated = "AUTHENTICATED";
        else
            isAuthenticated = "NOT AUTHENTICATED";
        rs.close();
    %>
    <html>
        <body>
        <h1><%= isAuthenticated %></h1>
        <hr>
        </body>
    </html>I am trying to get a String value for rs.getString() but for some reason this is not working out. Is there anything I can do to get the values for the queries in a String value?
    Thanks,
    Harlin

    When a ResultSet is returned to you, it is always positioned before the first row.
    You need to insert a rs.next(); after your executeQuery().

  • How do I know if I can convert a String value to an int value or not?

    Hi,
    I want to know how to make the judgment that if I can convert a String value to an int value or not? Assume that I don't know the String is number or letters
    Thank you

    Encephalopathic wrote
    Again, why?One of the problems (have been dued) in my codelab asks us to write a class as follow
    Write a class definition of a class named 'Value' with the following:
    a constructor accepting a single integer paramter
    a constructor with no parameters
    a method 'setVal' that accepts a single parameter,
    a boolean method, 'wasModified' that returns true if setVal was ever called for the object.
    a method 'getVal' that returns an integer value as follows: if setVal has ever been called, it getVal returns the last value passed to setVal. Otherwise if the "single int parameter" constructor was used to create the object, getVal returns the value passed to that constructor. Otherwise getVal returns 0.
    The setVal(int y) returns nothing, so how do I know whether it has been called or not?
    Thank you

  • Can't assign a string value to a member of type TEXT in Calculation Manager

    I can assign a string value to that member of type TEXT using a run-time prompt of type StringToNumber.
    Example: "My Text Member" = {string_rtp};
    However, I need to accompllish the same function without using a run-time prompts.
    I have a planning application and I know that text along with all other non-numeric
    values are stored on the relational side in the planning application schema.
    It seems reasonable to assume that if this can can accomplish
    with a run-time prompt that I could do also do it without a run-time prompt.
    What appears to be lacking is a function like:
    "My Text Member" = @StringToNumber(<String Literal>);
    Clearly, this is already being done "under the covers" for run-time prompts. If
    would appear to be a minor enhancement to expose such a function to developers.
    NOTE: I suppose you would also need to add new syntax/function to identify a string
    literal from say a member name. I'm wondering if this is the more difficult challenge
    from a product perspective????

    When executing a Calculation Manager rule in Planning, the run-time prompt (RTP) is populated by looking up the outline information present in the relational Planning application database. If the RTP is of type TEXT, the strings displayed in the member select are from the from the relational Planning application database too. Subsequently when executing the Rule, the RTP's value is in fact the record ID (a number) which is then saved into the appropriate intersection in Essbase.
    You need to bear in mind, the Rule is executed in Essbase. If Essbase needs to "write" a text, it would then need to connect to the Planning relational database to create a new record. The newly created record ID then needs to be feed back to Essbase, in order to store it in the appropriate intersection.
    What you are suggesting, comes with a big overhead causing Essbase and the rule to slow. Thus, the disadvantages outweighs the advantages.

Maybe you are looking for

  • Problem with syncing my calendar

    Hi, hope someone can help me I am having a problem syncing my blackberry calendar to the PC - the sync  goes so far then blocks, the message on screen is "synchronizing blackberry curve 8520 do not disconnect, organizer data progressing, converting b

  • Theme editor not showing

    Hi, NW2004s. We have restored DB and File-System. Now theme editor isn't showing anymore. But themes are in PCD and Personalization. Error see above. The problem ist described alread in thread <a href="https://www.sdn.sap.com/irj/sdn/thread?threadID=

  • Total orders in three weeks for a customer that was new three weeks ago.

    I need help figuring out the MDX to use to calculate this measure: Total orders in three weeks for customers that were new three weeks ago.   I seem to be having a brain freeze or over thinking this as usual.  My records have a customer, a date, a f

  • HP 2600n shared by Windows

    How can I use a HP 2600n shared by a Windows computer? Actually, I can't choose this model as it's not available from the Print Using pop-up menu.

  • Windows 7 sees my phone as my husband's..

    Windows 7 (64-bit) no longer recognizes my phone as the name that I originally set up for it. It sees it as my husband's phone. This only started after updating to iOS5 and the latest iTunes. Does anyone know how I can fix this? When we set up our ph