Java Comparator - Sorting - using predefined order

I want to sort the items in my list with a predefined order....Is it possible? I can sort my List using a natural sort as in the below example. But that is not am looking for.....Am looking for sorting my list using an already defined order which i can hold using another list. IS IT POSSIBLE USING Comparator
package com.nationwide.ag.integration.adapter.party;
import java.util.*;
public class TestUsingMe {
static class AppComparator implements
Comparator {
public int compare(Object o1, Object o2) {
int cc = ((Integer)o1).compareTo(o2);
return (cc < 0 ? 1 : cc > 0 ? -1 : 0);
static Comparator appcomparator =
new AppComparator();
static void sort(List list1) {
Collections.sort(list1, appcomparator);
public static void main(String[] args) {
List list1 = new ArrayList();
list1.add(new Integer(90));
list1.add(new Integer(43));
list1.add(new Integer(21));
sort(list1);
System.out.println(list1);
Please reply................

Tried as per your advice, as below. But, it didn't work out. (Hope I have done the changes correctly). Please find the changed code below:
import java.util.*;
import com.dto.search.PersonDTO;
public class TestUsingMe {
public static void main(String[] args) {
     PersonDTO pDTO0 = new PersonDTO();
     pDTO0.setCifId("Named Non-Owner");
     PersonDTO pDTO1 = new PersonDTO();
     pDTO1.setCifId("Restored");
     PersonDTO pDTO2 = new PersonDTO();
     pDTO2.setCifId("Antique/Classic");
List list1 = new ArrayList();
list1.add(pDTO0);
list1.add(pDTO1);
list1.add(pDTO2);
List list2 = new ArrayList();
list2.add("Private Passenger");
list2.add("Restored");
list2.add("Antique/Classic");
list2.add("Named Non-Owner");
list2.add("Trailer");
AppComparator appcomparator = new AppComparator(list2);
Collections.sort(list1, appcomparator);
static class AppComparator implements Comparator {
private List list;
public AppComparator(List list) {
this.list = list;
public int compare(Object o1, Object o2) {
return list.indexOf("cifId") - list.indexOf("cifId");
Please respond...................

Similar Messages

  • How java Comparator is used ?

    Here is a compare method of a Comparator
    class AgeComparator implements Comparator{
        public int compare(Object emp1, Object emp2){
             * parameter are of type Object, so we have to downcast it
             * to Employee objects
            int emp1Age = ((Employee)emp1).getAge();       
            int emp2Age = ((Employee)emp2).getAge();
            if(emp1Age > emp2Age)
                return 1;
            else if(emp1Age < emp2Age)
                return -1;
            else
                return 0;   
    Question: How does these return  makes a list in ascending / descending order ?
    We use the above comparator this way.
            //Employee array which will hold employees
            Employee employee[] = new Employee[2];
            //set different attributes of the individual employee.
            employee[0] = new Employee();
            employee[0].setAge(40);
            employee[0].setName("Joe");
            employee[1] = new Employee();
            employee[1].setAge(20);
            employee[1].setName("Mark");
            //Sorting array on the basis of employee age by passing AgeComparator
            Arrays.sort(employee, new AgeComparator());

    user575089 wrote:
    If so, I dont get the point why a FLAG return > is mapped with a ascending order ? whats the analogy here ?There's no "analogy." It's just convention. The rules say, "Our sort routine will ask you which of two objects is "less". If you return a negative number, we will take that to mean that the first object is "less than" the second," and so on.
    Imagine someone gives you a deck of cards that's been shuffled and tells you to put it back in order. What would that order look like?
    It might be:
    A-spades
    2-spades
    3-spades
    K-spades
    A-clubs
    and so on. That is, you might sort first by suit, then by rank, with spades being "less than" clubs, and so on.
    Or it might be:
    A-spades
    A-clubs
    A-hearts
    A-diamonds
    2-spades
    with all the aces first, and the cards of the same rank being ordered by suit according to some rule.
    Now, stop and think about the actual process of sorting the cards. There are several different approaches, but many of them involve the step: "Compare card X with card Y, and if they're in the wrong order, switch them." You understand that, right?
    That is, if you're physically sorting cards, you will look at two cards, determine which one should come first, because it's "less than" the other card by whatever rules you're using, and then, if those cards are in the wrong order, you switch them. Do you understand this?
    Now, if you understand that, do you understand that you can apply that step no matter what rules you have for determining which card is "less than" the other. In the first sample order I gave above, you might have the Ace of Diamonds in your left hand, and the King of Spades in your right. Since all Spades come first, you would switch them. But in the second example ordering, the rules say that all Aces come before anything else, so you would not switch them.
    Your algorithm is: "Pick two cards, and if they're in the wrong order, switch them." That is, "if the one in the lower position is 'greater than' the other one, then switch them.".
    That's what Arrays.sort() and Collections.sort() and SortedSet and SortedMap do. All that your Comparable.compareTo() or Comparator.compare() method does is tell the sort() methods which object is "less".
    For example:
    Card c0 = cardList.get(0);
    Card c1 = cardList.get(1);
    // if the card at position 0 is "greater than" the card at position 1...
    if (c0.compareTo(c1)) > 0) {
      // ... then switch c0 with c1
    }Of course, the indices aren't hardcoded, and the choice of which pairs to compare is done intelligently, so that we will, on average, not make too many unnecessary comparisons, but this is the basic idea.

  • Sorting in numbers using a predefined order.

    I've seen this question posted, but without a solution beyond, send it to tech support for a suggestion.  That being said, I'm reposting to see if anyone has come up with something.
    Let's say I have this table:
    Fruit
    Name
    Banana
    Joe
    Apple
    Brittany
    Orange
    Scott
    Banana
    Ted
    Apple
    Molly
    I want to PREDEFINE the sorting order:
    Orange
    Apple
    Banana
    Then I want to sort that way.  Sorting by Categories IS NOT how I want this to happen.
    Can this happen?  How does this happen?

    Mike,
    Add a column, Hidden if you prefer, and in that new column enter letters or numbers to define the preferred sort order. When it comes time to sort, use that column. You may need a different sort order defining column for each list that you want to define an order for.
    Jerry

  • How to sort random number without the used of order by

    Hi ,
    how should 5 random number be sorted without the use of order by in PLSQL
    eg.
    id amount
    1 2
    2 9
    3 3
    4 5
    5 7
    Edited by: sake1 on 1-dec-2010 8:16

    I used Altavista and found one example, how does it look?
    DECLARE
      /* there is no built array in oracle, you must declare
      your own */
      TYPE Numarray IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;
      /* the array of numbers - using assoc array because I can start
      with zero like traditional arrays */
      Nums Numarray;
      n NUMBER := 0;
      Temp NUMBER;
    BEGIN
      /* load up the array, put 20 random values in the array,
      in array indicies 0 to 19 */
      FOR i IN 0 .. 19
       LOOP
        Nums(i) :=  Round(Dbms_Random.Value(1, 1000));
      END LOOP;
      /* get the array size */
      n :=  Nums.Count();
      /* display the unsorted values - loop through the whole array and
      print out the values */
      Dbms_Output.Put_Line('unsorted:');
      FOR i IN Nums.First .. Nums.Last LOOP
        Dbms_Output.Put_Line(Nums(i));
      END LOOP;
      /* bubble sort - using two loops, compare each value with the one
      after it
      if the one after the current one is smaller , then
      switch their locations in the array, this is just like standard
      bubble sorts
      in other languages. The only real diff is the syntax.
      FOR i IN 0 .. n - 1 LOOP
        FOR j IN 0 .. n - (i + 1) - 1 LOOP
          IF (Nums(j) > Nums(j + 1)) THEN
            Temp := Nums(j);
            Nums(j) :=  Nums(j + 1);
            Nums(j + 1) :=  Temp;
          END IF;
        END LOOP;
      END LOOP;
      /* display the values sorted */
      Dbms_Output.Put_Line('sorted');
      FOR i IN Nums.First .. Nums.Last LOOP
        Dbms_Output.Put_Line(Chr(9) || Nums(i));
      END LOOP;
    END;
    unsorted:
    155
    909
    795
    977
    942
    214
    105
    269
    283
    820
    108
    594
    784
    921
    856
    736
    802
    457
    951
    411
    sorted
         105
         108
         155
         214
         269
         283
         411
         457
         594
         736
         784
         795
         802
         820
         856
         909
         921
         942
         951
         977
    */In the code the first comment is wrong actually i think, that one:
    "there is no built array in oracle, you must declare your own"
    I remember there were some system collection-types, if i'm not mixing with something, i remember there was some kind of such but they were un-documented ones, so we can juridically say that the comment in the code was still correct.

  • The sort field is not used when ordering multiple cds in one alumn folder, how do I correct this?

    It is using the track number and not the sort order field.  The reason I have multiple cds in one alumn is because they are books on cd.

    Sorry for the typo my "b" key was not working correctly.
    The sort field is not used when ordering multiple cds in one albumn folder, how do I correct this?  It is using the track number and not the sort order field.  The reason I have multiple cds in one albumn is because they are books on cd.

  • Find row in Dataview using ID but Name sorted in alphabetical order

    Hi,
    I have a dataview with 2 columns, ID and Name, where it is sorted by"Name".
    I want to find a row using the ID, namely curID. But the following doesn't seem to work, as I believe my dataview was sorted using the Name column. How can I sort the dataview with "Name", but be still be able to "Find" using its ID?
    dv.Sort = "ID ASC"
    rowIndex = dv.Find(curID)
    Please advice. Your help would be greatly appreciated.

    Use a plain old for loop then. You could define your own method:
    private static DataRowView FindRow(DataView dv, int id)
    foreach (DataRowView rowView in dv)
    if (Convert.ToInt32(rowView["ID"]) == id)
    return rowView;
    return null;
    And call it like this:
    DataRowView dataRowView = FindRow(dv, curID);
    if(dataRowView != null)
    //found...
    Please remember to mark all helpful posts as answer and/or helpful.

  • Radix sort using integers

    Cany anyone help me convert my code to sort using integers and maybe using a Queue?
    Thanks in advance, I appreciate it.
    import java.util.*;
    public class RadixSort{
      String[] input;
      int maxLength;
      public RadixSort(String[] sa){
        input = sa;
        maxLength = input[0].length();
        for (int i = 1; i < input.length; ++i){
          if (input.length() > maxLength){
    maxLength = input[i].length();
    public String[] sort(){
    for (int i = maxLength -1; i > -1; --i){ //begin compare from the last char
    Arrays.sort(input, new RadixComparator(i));
    return input;
    // give two or more strings as command line args
    // ex. java RadixSort vouch wacky lover love banana ananas
    public static void main(String[] args){
    RadixSort rs = new RadixSort(args);
    String[] result = rs.sort();
    for (int i = 0; i < result.length; ++i){
    System.out.println(result[i]);
    class RadixComparator implements Comparator{
    int columnNum; //start from 0
    public RadixComparator(int col){
    columnNum = col;
    public int compare(Object o1, Object o2){
    char c1, c2;
    String s1 = (String)o1;
    String s2 = (String)o2;
    int l1 = s1.length();
    int l2 = s2.length();
    if (l1 < (columnNum + 1)){ //s1 too short
    if (l2 < (columnNum + 1)){ //both too short
    return 0;
    else{
    return -1;
    else if (l2 < (columnNum + 1)){ //s2 too short
    return 1;
    else{
    c1 = s1.charAt(columnNum);
    c2 = s2.charAt(columnNum);
    return (c1 - c2);

    sort using integersIf your integer set only contains positive numbers, you could readily use radix sort for strings for
    them. You could easily convert int[] to String[] and vice versa. If your integer set is a mix of
    positives and negatives, then you would have to run radix sort twice and concatenate the
    results. One for positives, and anothe for negatives -- the latter should be a reverse
    radix sort because -1234 is larger than -5678.

  • Verifier Error: Exception handlers not sorted in ascending order by the off

    Hello,
    Java Card 2.2 did not convert my Applet !
    Java Card 2.2.1 & 2.1.2 do not report this Error and the Applet is working !
    What's wrong here ?
    D:\save\smsTest>C:\Programme\Java\jdk1.5.0_06\bin\java -classpath D:\java_card_kit-2_2\lib\converter.jar;D:\java_card_kit-2_2\lib\offcardverifier.jar com.sun.javacard.converter.Converter -config SMS_JCDK_2_2.opt
    Java Card 2.2 Class File Converter (version 1.3)
    Copyright 2002 Sun Microsystems, Inc. All rights reserved. Use is subject to license terms.
    warning: You did not supply export file for the previous minor version of the package
    parsing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\IExceptionConstants.class
    parsing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\ITestConsts.class
    parsing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\InfoData.class
    parsing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\SMS.class
    parsing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\StringConsts.class
    converting com.gieseckedevrient.jctt.smsTest.IExceptionConstants
    converting com.gieseckedevrient.jctt.smsTest.ITestConsts
    converting com.gieseckedevrient.jctt.smsTest.InfoData
    parsing D:\java_card_kit-2_2\api_export_files\java\lang\javacard\lang.exp
    converting com.gieseckedevrient.jctt.smsTest.SMS
    parsing D:\java_card_kit-2_2\api_export_files\javacard\framework\javacard\framework.exp
    parsing U:\_Tools\java\43019-560\Annex_B_Export_Files\sim\toolkit\javacard\toolkit.exp
    converting com.gieseckedevrient.jctt.smsTest.StringConsts
    writing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\javacard\smsTest.exp
    writing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\javacard\smsTest.jca
    Verifier Error: Exception handlers not sorted in ascending order by the offset of the handler
    Verification failed

    Hello again,
    it seams this error only occurs when using javac from JDK 1.5/1.6 (1.4 not tested).
    When I us jdk1.3.1_11 to compile the java sources this error never occurs during conversion !

  • Vector sorting in given order

    Lets say i have something like this
    A[]=[z,y,z,x,z,w,x,z,x,w,y];
    I would like to get in the given order
    like
    A[]=[z,z,z,z,w,w,w,x,x,x,x,y,y,y,y]
    If you see what i am saying....i want sorting in given order...i am using vector....
    Finding the way to appreciate your solution....
    thx
    Su

    Cross posted http://forum.java.sun.com/thread.jspa?threadID=753115

  • Java ebcdic sort

    Hi, I am trying to do a sort in ebcdic order instead of ascii order. The elements to be sorted are in a array. So what can i do to sort this in ebcdic order?
    in addition what techniques should give the best sorting time? in a array, vector, or collection? and how to do that?
    Thanks

    These "elements" are Strings, I suppose. Then for each string make a corresponding byte array like this:byte[] ebcdic = theString.toBytes("cp500");and put these byte arrays into some kind of collection -- an array might be suitable since you know the size in advance. Then sort that array using Arrays.sort(). Since there is no "natural ordering" for byte arrays, I don't think there is anyway, you will have to write a Comparator to help it out. Like this:public class ByteArrayComparator implements Comparator {
      public int compare(Object�o1, Object�o2) {
        byte[] b1 = (byte[])o1;
        byte[] b2 = (byte[])o2;
        len1 = b1.length;
        len2 = b2.length;
        complen = (len1 < len2 ? len1 : len2);
        for (int j=0; j<complen; j++) {
          int diff = b1[j] - b2[j];
          if (diff != 0) {
            return diff;
        return len1 - len2;
      public boolean equals(Object o) {
        return this == o;
    }Your sorting code would beArrays.sort(yourArrayofArrays, 0, yourArrayofArrays.length, new ByteArrayComparator());When you're done, make the byte arrays back into Strings, keeping them in the same order, and you're done.

  • How to Exclude Java Reserved Words Using StringTokenizer

    Hi, i'm trying to exclude identifiers and java reserved words using StringTokenizer from an input file outputting the remaining words alphabetically ordered with the line, on witch they occur, in front of the word.
    So far my code does all that, except exclude those words. I'm kind on a dead end... Any suggestions?
    The code:
    public class Interpreter{
        /* Uses a Binary Search Tree      */
        public static void main(String args[ ]) {
            String path = null;
            for (int j = 0; j < args.length; j++) {
                try {
                    // Step 1, read the input file
                    path   = args[j];
                    FileReader input = new FileReader(args[j]);
                    BufferedReader br = new BufferedReader(input);
                    String line;
                    int count = 1;
                    String word;
                    // Step 2, create an empty Tree
                    BST tree = new BST();
                    while((line = br.readLine())!=null){
                        StringTokenizer str = new StringTokenizer(line);
                        while (str.hasMoreTokens()){
                            word = str.nextToken();
                            tree.insert(word,count);
                        count++;
                    // We're done, print out contents of Tree!
                    tree.print();
                    // Error Handling
                    //check for IO problem with bad file
                } catch (IOException e) {
                    System.out.println("There was a problem with the filename you entered.");
                    //check for no filename entered at command prompt
                } catch (ArrayIndexOutOfBoundsException e) {
                    System.out.println("Please include a filename when running this program.");
    }Edited by: Redol on Dec 12, 2007 8:32 PM
    Edited by: Redol on Dec 12, 2007 8:33 PM

    use split instead of tokenizer.
    public String[] splitString( String line, String delim )
        String[] tokens = null;
        if( line != null )
            tokens = line.split( delim );
        return tokens;
    }

  • How to compare dates using javascript?

    Hi,
    I have to compare dates using javascript. The dates are in format "mm/dd/yy" for eg "10/09/06".
    I have written a script to compare the dates but the problem I 'm facing is with the year.
    For example if I compare "10/09/06" with "10/04/98", then "10/04/98" is coming out to be greater than "10/09/06" because it is considering year "98" to be greater than "06".
    Please advice/suggest.
    Thanks in advance...

    Dude, you're here in a Java forum, not in a Javascript forum. Those are two entirely different languages.
    The answer in Java is to use java.text.SimpleDateFormat to convert String to Date and use java.util.Date and/or java.util.Calendar to compare dates.

  • Is an index used in ORDER BY

    Hi all,
    I was wondering if an index is used in ORDER BY clause?
    Thanks

    Dear,
    Sometimes the Oracle Optimizer use the index to avoid doing the sort order by; see the following example
    SQL> desc t1
    Nom                           NULL ?   Type
    A                             NOT NULL VARCHAR2(8)
    B                             NOT NULL NUMBER
    SMALL_VC                               VARCHAR2(10)
    PADDING                                VARCHAR2(100)
    There exist two indexes on this table
    t1_Pk (a,b) and t1_ba(b,a)
    SQL> select *
      2  from t1
      3  where b = 14
      4  order by a;            
    316 ligne(s) sélectionnée(s).
    SQL> set linesize 120
    SQL> select * from table(dbms_xplan.display_cursor);
    PLAN_TABLE_OUTPUT                                                                                                      
    SQL_ID  1cunkbn7x2206, child number 0                                                                                  
    select * from t1 where b = 14 order by a                                                                               
    Plan hash value: 1994226220                                                                                            
    | Id  | Operation                    | Name  | Rows  | Bytes | Cost (%CPU)| Time     |                                 
    |   0 | SELECT STATEMENT             |       |       |       |   320 (100)|          |                                 
    |   1 |  SORT ORDER BY               |       |   315 | 39375 |   320   (1)| 00:00:04 |                                 
    |   2 |   TABLE ACCESS BY INDEX ROWID| T1    |   315 | 39375 |   319   (0)| 00:00:04 |                                 
    |*  3 |    INDEX RANGE SCAN          | T1_BA |   315 |       |     3   (0)| 00:00:01 |                                 
    Predicate Information (identified by operation id):                                                                    
       3 - access("B"=14)                                                                                                  
    20 ligne(s) sélectionnée(s).
    SQL> select *
      2  from t1
      3  where a = '20110101'
      4  and   b between 1 and 14
      5  order by a;                                                              
    14 ligne(s) sélectionnée(s).
    SQL> select * from table(dbms_xplan.display_cursor);
    PLAN_TABLE_OUTPUT                                                                                                      
    SQL_ID  ad6v4jyuwu9a1, child number 0                                                                                  
    select * from t1 where a = '20110101' and   b between 1 and 14 order by                                                
    a                                                                                                                      
    Plan hash value: 785719456                                                                                             
    | Id  | Operation                   | Name  | Rows  | Bytes | Cost (%CPU)| Time     |                                  
    |   0 | SELECT STATEMENT            |       |       |       |     3 (100)|          |                                  
    |   1 |  TABLE ACCESS BY INDEX ROWID| T1    |    14 |  1750 |     3   (0)| 00:00:01 |                                  
    |*  2 |   INDEX RANGE SCAN          | T1_PK |    14 |       |     2   (0)| 00:00:01 |                                  
    Predicate Information (identified by operation id):                                                                    
       2 - access("A"='20110101' AND "B">=1 AND "B"<=14)                                                                   
                                                        See how in the seconde select, how when the index t1_pk has been used there is no sort order operation within the explain plan. I beleive that the index t1_pk has been used to order by a the results
    Best Regards
    Mohamed Houri

  • Parameters to be sorted in alphabetical order

    Hi,
    Can you please let me know whether the parameters values are by default sorted in alphabetical order...refering to discoverer viewer/plus...
    Thanks in advance
    Sri

    If you are referring to the item classes (list of values), they would be sorted in alphabetical order. The parameter values wud appear in the same order in which the lovs appear in admin.
    If you want to customize the sorting (reorder), you can do so using alternate sort tab in edit item class.
    you can refer to the admin users guide.

  • Can't sort photos in order TAKEN in Finder

    I hope some of you super smart MacBook Pro users will be able to help me...
    I just made the switch from a windows laptop to a Macbook Pro, and while I am very happy with my decision, I am still working on that learning curve.
    I am a photographer who uses Adobe Bridge to cull photos (by giving them star ratings) and Adobe Photoshop to process. I recently shot a wedding using two different cameras simultaneously.  I synced the time on the cameras prior to starting the shoot so that the photos of the entire day would be sorted in time order when saving them and burning them onto a disc.
    I used three memory cards throughout the day and processed all of the photos off one card before moving on to the next, so the photos were not processed in chronological order. I shoot in RAW and run batches that save the final photo as JPEG.
    I would like to burn these files to a disc in chronological order. I have created a folder in Finder where all of the photos are located. I am unable to sort the files by DATE TAKEN. There is an option for DATE CREATED, but the date it shows is the date the JPEG file was created, not the date the photo was taken. When I click on a file and look at its file info, the DATE TAKEN is not shown, just this same date that the JPEG file was created. However, when I look in Photoshop at the file info, the DATE CREATED is indeed the actual time that the photo was snapped during the wedding.
    Does anyone know how I can get this information into Finder? Is there another "Explorer" type software I should be using to make this work? Is there a better way to burn files to disc than using Finder?

    I only have iPhoto but I have imported two different sd cards into iphoto and then merged the events into one event and iPhoto arranged them in cronological order even though the raw file names were different. then I exported the event to a file and burned them. if you have the sd cards with the original photos maybe this will work for you

Maybe you are looking for