Sorting TreeMap

Hi,
I've been trying to work this out and can't seem to find a solution. I have a treemap of object and I want to sort them by their names, such as lastname. These object hold all these datas. I wrote myself a comparator class like this:
import java.util.*;
import java.io.*;
public class PatientComparator implements Comparator {
public int compare(Object obj1, Object obj2) throws ClassCastException {
System.out.println(obj1.getClass()); //use to see what is passing in to compare
Patient a = (Patient)obj1;
Patient b = (Patient)obj2;
String nameA = a.getName();
String nameB = b.getName();
String firstName = nameA.substring(0,nameA.indexOf(",",0)-1);
String lastName = nameA.substring(nameA.indexOf(",",0)+1,nameA.length()-1);
String firstName2 = nameB.substring(0,nameB.indexOf(",",0)-1);
String lastName2 = nameB.substring(nameB.indexOf(",",0)+1,nameB.length()-1);
int result = 0;
if ( !(lastName.equals(lastName2)) )
     result = lastName.compareTo(lastName2);
else
result = firstName.compareTo(firstName2);
return result;
I have to use TreeMap or HashMap right now because they both utilize the assigned key to identify object quicker. But the culprit is how do I sort this TreeMap in term of object properties(like name, age). Here is the class I implement it:
public class DoctorsOffice {
private String office_name;
private int ID = 1000; //start out with id # 1000
private SortedMap active = new TreeMap(new PatientComparator());
//private SortedSet inactive = new TreeSet();
* Constructor for a DoctorsOffice object.
* @param name Name of this Dr's Office
public DoctorsOffice (String name) {
office_name = name;
* Add a new patient to the office. The identification
* number is uniquely generated and is returned when the
* Patient object is added to the database. ID numbers
* start at 1000 and increment by one for each new Patient
* added.
* @param firstName first name of this patient
* @param lastName last name of this patient
* @param age age of this patient
* @return the ID number assigned to this Patient
public int addPatient (String firstName, String lastName, int age) {
Patient new_patient = new Patient( firstName,lastName,age );
active.put( new Integer(ID), new_patient );
ID++;
return (ID - 1);
* Remove this patient from the master database. Removed patients are
* archived in an "inactive" database which maintains Patron
* objects in the order in which they were removed from the master
* database.
* @param patientNo     Patient number assigned
* @exception throws a NoSuchPatientException
* if this patient does not exist
public void removePatient (int patientNo)
throws NoSuchPatientException {
* Add a new medication for this patient.
* @param patientNo     Patient number
* @param medicationName     Name of this medication
* @param isGeneric     True if a generic drug
* @exception throws NoSuchPatientException if
* this patient ID does not exist.
public void addMedication(int patientNo, String medicationName,
     boolean isGeneric ) throws NoSuchPatientException {
if ( active.containsKey(new Integer(patientNo)) ) {
((Patient)active.get(new Integer(patientNo))).recordNewMed(
medicationName, isGeneric );
else
     throw new NoSuchPatientException();
* Print the medication detail for this patient. Print
* the patient's full name (lastname COMMA SPACE firstName)
* then each medication (each one on a new line). To print
* the medications, simply call your toString() method in
* the Medication class.
* If this patient has no medication history, print "No Medications
* Prescribed".
* @param patientNo     Patient number
* @exception throws NoSuchPatientException
* if patient does not exist.
public void printMedicationDetail (int patientNo)
     throws NoSuchPatientException {
Integer patientID = new Integer(patientNo);
if ( active.containsKey(patientID) ) {
System.out.println( ( (Patient)active.get(patientID)).getName() );
((Patient)active.get(patientID)).printMedicationHistory();
else
throw new NoSuchPatientException();
* Print all patients ordered by last name, then first name if
* you encounter two patients with the same last name.
* To print the Patient objects, simply call your toString() method
* in the Patient class.
public void listByName() {        
     // Collection coll = active.values();
// List temp = new ArrayList(coll);
     // sort(temp,new PatientComparator());
// Set s = temp.keySet();
Iterator iterator = active.iterator();
while( iterator.hasNext() ){
     // String key = (String)iterator.next();     
     System.out.println(iterator.next());     
}

I guess I go with the easiest way to do it. But here's
another culprit, since values() method turn my
TreeMap into a collection(interface), It doesn't turn the TreeMap into anything. That is, the original TM still exists, exactly as you left it. There's just a new Collection created that refers to each of the TM's values.
and the sort()
method is in class Collections, how do I call the
sort(), and also the sort() method has two parameters
(List list, Comparator C)If your values implement Comparable, and you want to use the natural sort order (for instance, the values are Strings and you just want them sorted alphabetically), then you just call the sort method that takes a single List parameter. Otherwise (for instance, you want to reverse the sort order, or sort by length, etc.), you have to write a Comparator for your values.
>
1st) I don't have any list to put as parameter.Both LinkedList and ArrayList take a Collection as a constructor arg, I think, so you can construct one from the Collection returned by values().
2nd) Comparator C will keep comparing two keys from
the treemap or in the collection?
Collection coll = active.values();
Collections.sort( , new
PatientComparator());The TreeMap's Comparator will do that. The values List will sort however you tell it to, regardless of how the TreeMap sorts its keys.
I don't think the sort is able to be called this way,
and what do I substitute in for a parameter list when
I have a treemap right now? Huh?

Similar Messages

  • Re: sorting TreeMap

    You can't exactly sort a TreeMap because it's order is fixed as it's built. It's maintained in order, you don't sort it.
    However you can supply a Comparitor object but it will need to define a full ordering of the keys. You could create a secondary TreeMap with a Comparitor which looked up the product code in a simple TreeMap and retrived and compared the priorities.
    I think what I'd do is to define a class to contain the fields of each record. You can then simply store these records in an ArrayList or LinkedLIst which will maintain them in the order which the database has sorted for you.
    If you want to also be able to access them by, say, product code then build a Map as you read them in to provide that as a secondary access.

    ... still i'm curious abt the TreeMap code.
    Can anyoneone send me
    the example, if possible.The following shows a TreeMap sorts Hashmap..
    import java.util.*;
    public class HashToTree {
    private java.util.HashMap hashMap;
    /** The tree map to sort data. */
    private java.util.TreeMap treeMap;
    public void demonstrate(){
    hashMap = new HashMap();
    hashMap.put("Key2", "2");
    hashMap.put("Key4", "4");
    hashMap.put("Key1", "1");
    hashMap.put("Key3", "3");
    //Sort the hash map using a tree map
    treeMap = new TreeMap(hashMap);
    public static void main(String[] args) {
    HashToTree hash_tree = new HashToTree();
    hash_tree.demonstrate();
    System.out.println("HashMap: " + hash_tree.hashMap);
    System.out.println("TreeMap: " + hash_tree.treeMap);
    }

  • Help needed for storing and sorting objects.

    Hello
    I have an assignment and it is to create a guessing game, here is the question,
    In this assignment you are to write a game where a user or the computer is to guess a random
    number between 1 and 1000. The program should for example read a guess from the keyboard, and
    print whether the guess was too high, too low or correct. When the user has guessed the correct
    number, the program is to print the number of guesses made.
    The project must contain a class called Game, which has only one public method. The method must
    be called start(), and, when run it starts the game. The game continues until the user chooses to
    quit, either at the end of a game by answering no to the question or by typing 'quit' instead of a
    guess. After each game has been played, the program is to ask the user for a name and insert this
    together with the number of guesses into a high score list. When a game is started the program
    should print the entire high score list, which must be sorted with the least number of guesses first
    and the most last. Note, the list must be kept as long as the game-object is alive!
    each score also
    consists of the game time. In case there are two high scores with the same number of guesses, the
    game time should decide which is better. The game time starts when the first guess is entered and
    stops when the correct guess has been made. There should also be input checks in the program so
    that it is impossible to input something wrong, i.e. it should be impossible to write an non-numeric
    value then we are guessing a number, the only allowed answers for a yes/no question is yes or no,
    every other input should yield an error message an the question should be printed again.
    I understand how to code most of it, except I am not sure how to store the playerName, playerScore, playerTime and then sort that accordingly.
    I came across hashmaps, but that wont work as the data values can be the same for score.
    Is it only one object of lets say a highScore class, and each time the game finishes, it enters the values into an arrayList, I still dont understand how I can sort the array all at once.
    Should it be sorted once for score, then another array created and sorted again, I dont get it I am confused.
    Please help clarify this.

    Implode wrote:
    We had the arrayList/collections lecture today.
    I asked the teacher about sorting objects and he started explaining hashmaps and then he mentioned another thing which we will only be learning next term, I'm sure we must only use what we have learned.
    How exactly can this be done. I have asked a few questions in the post already.
    ThanksWell, there was probably a gap in the communication. Hash maps (or hash tables, etc.) are instance of Map. Those are used to locate a value by its unique key. Generally, to speed up access, you implement a hashing function (this will be explained hopefully in class). Think of name-value pairs that are stored where the name is unique.
    Contrast this with items that are sorted. Any List can be sorted because its elements are ordered. An ArrayList is ordered, generally, by the order you inserted the elements. However, any List can be given its own ordering via Comparable or Comparator. You can't do this with an ordinary Map. The purpose of a Map is speedy access to the name-value pairs, not sorting. The List likewise has different purposes, advantages, disadvantages, etc. List can be sorted.
    A Map is generally similar to a Set. A Set is a vanilla collection that guarnatees uniqueness of each element (note, not name-value pairs, but simple elements). There is one concrete class of Map that can be sorted, TreeMap, but I doubt your professor was referring to that. The values or the keys can be returned from the Map and sorted separately, but again, I doubt he was referring to that.
    Take a look at the Collections tutorial here on this site or Google one. It is fairly straightforward. Just keep in mind that things (generally) break down into Set, Map and List. There are combinations of these and different flavors (e.g., Queue, LinkedHashMap, etc.) But if you can learn how those three differ, you will go a long way towards understanding collections.
    (Oh, and be sure to study up on iterators.)
    - Saish

  • Questions to TreeMap

    Hello,
    I have two questions to TreeMap.
    1:
    within my TreeMap I have sorted Key as a String and Value as an Integer. TreeMap sort that (per default, think so) to the Keys. Is it possible to sort that to the "Value".?
    2.
    I need different TreeMaps for different files and they must be associated with that files. I have a counter within my code which count the files. It is called "anzahl". this is an "int". If I want to take that as the name of an TreeMap in that way:
    TreeMap anzahl = new TreeMap();I get the error-message:
    WordFrequency.java:31: anzahl is already defined in main(java.lang.String[])
                    TreeMap anzahl = new TreeMap();
                            ^
    WordFrequency.java:168: int cannot be dereferenced
                                            anzahl.putAll(Vektoren);What I have to do that I can associate the Files with the treeMaps ?
    Thanks for helping,
    Stephan

    1) You cannot directly use values to sort TreeMaps. At any point in time you can instead get a the
    entrySet, put its elements in a List and sort it using a homegrown (i.e. write it yourself) Comparator that
    can compares elements by the value of the Map.Entry. This is just one way to do this.I agree
    2) The error message states that you already defined the variable name "anzahl" as an int. You need to > choose another name for your TreeMap.Not true. Two errors:
    First, anzahl was defined as a TreeMap (first line of code you posted) so you need not (and cannot) redifine it (even as a TreeMap, again) later on, delete "TreeMap" from the second line where it appears.
    Second, you may not put an int in a TreeMap, keys and values MUST be objects, so you'll have to use a wrapper, eg. Integer. I have no idea what "Vektoren" is (and if its a variable, it shouldn't be capitalized) but it seems to me your TreeMap thinks it's an 'int'.

  • Help needed for translation of custom objects

    Hi All,
    We are currently in the process of upgrading from 11i to R12.1.3. We have a lot of custom reports and forms which needs to be translated based on language preference set at user level. The approach we have taken is as follows:
    1. Created one unique look up type for each of the custom objects.
    2. Each lookup code is mapped to a field of the custom object (report or form).
    3. Entered the translation for each of the lookup codes using Globe icon (Translation Form) available on the lookup form.
    4. When the user logs into his account, we are filterting out the record specific to user environment language using the condition:
    language of fnd_lookup_values = usernev('lang') and getting the translated labels for each of the fields in the custom object.
    Now what we would like to understand is if there is any other better way of doing translation based on user preferred language.
    We have heard about Oracle Translation Manager (OTM) but not sure how the same can be used in our case. Also we would like to know how Oracle does translation for the languages that are enabled in a particular instance. We would like to know if a similar approach can be followed for custom objects as well.
    Thanks & Regards,
    Sreenivasa M

    Implode wrote:
    We had the arrayList/collections lecture today.
    I asked the teacher about sorting objects and he started explaining hashmaps and then he mentioned another thing which we will only be learning next term, I'm sure we must only use what we have learned.
    How exactly can this be done. I have asked a few questions in the post already.
    ThanksWell, there was probably a gap in the communication. Hash maps (or hash tables, etc.) are instance of Map. Those are used to locate a value by its unique key. Generally, to speed up access, you implement a hashing function (this will be explained hopefully in class). Think of name-value pairs that are stored where the name is unique.
    Contrast this with items that are sorted. Any List can be sorted because its elements are ordered. An ArrayList is ordered, generally, by the order you inserted the elements. However, any List can be given its own ordering via Comparable or Comparator. You can't do this with an ordinary Map. The purpose of a Map is speedy access to the name-value pairs, not sorting. The List likewise has different purposes, advantages, disadvantages, etc. List can be sorted.
    A Map is generally similar to a Set. A Set is a vanilla collection that guarnatees uniqueness of each element (note, not name-value pairs, but simple elements). There is one concrete class of Map that can be sorted, TreeMap, but I doubt your professor was referring to that. The values or the keys can be returned from the Map and sorted separately, but again, I doubt he was referring to that.
    Take a look at the Collections tutorial here on this site or Google one. It is fairly straightforward. Just keep in mind that things (generally) break down into Set, Map and List. There are combinations of these and different flavors (e.g., Queue, LinkedHashMap, etc.) But if you can learn how those three differ, you will go a long way towards understanding collections.
    (Oh, and be sure to study up on iterators.)
    - Saish

  • Sorting problem in TreeMap, please help urgent :-((

    Hi
    Following is a program, please execute it to see the problem. I am adding four elements in the TreeMap. The problem is when I add the elements it never compares the newly added element with the first element. I was sick of it so to test the TreeMap I created my own small class and defined a Comparator for that class. Following is the code which shows the problem in TreeMap. Am I doing something wrong? Please help its urgent.
    import java.util.*;
    public class SortingCollection {
         public static void main(String[] args) {
              SortingCollection sortingCollection = new SortingCollection();
              sortingCollection.sortingTest();
         public void sortingTest() {
              TreeMap treeMap = new TreeMap();
              treeMap.put(new Test("Bhushan", 1022), new Integer(1022));
              treeMap.put(new Test("Wasil", 1023), new Integer(1023));
              treeMap.put(new Test("Ifti", 1020), new Integer(1020));
              treeMap.put(new Test("Roshan", 1021), new Integer(1021));
              System.out.println(treeMap);
              Test test = new Test("Bhushan", 1028);
              treeMap.put(test, new Integer(1022));
              System.out.println(treeMap);
         public class Test implements Comparable {
              public String name;
              public int age;
              public Test(String name, int age) {
                   this.name = name;
                   this.age = age;
              public int compareTo(Object toBeCompared) {
                   Test casted = (Test) toBeCompared;
                   if (name.equals(casted.name)) {
                        System.out.println("Returning 0 for " + name + " " + casted.name);
                        return 0;
                   System.out.println("Returning -1 for " + name + " " + casted.name);
                   return -1;
              public String toString() {
                   return "[" + name + ", " + age + "]";
    }

    If you are using TreeMap, you should want the keys to be immutable. You can't change the state of the keys of a Map such that their natural order will change, or chaos will happen.
    If the key is the GateKeeperInfo class (which has host, port, and # of users as its data members) and the value is "some other object reference which you need", and this reference is closely tied to the GateKeeperInfo, have you considered making it a member of the GateKeeperInfo?
    That way you don't need this TreeMap business. You can have the natural ordering imposed on the GateKeeperInfo class (which is apparently comparing the host and port only). You can also have a Comparator object that can compare these objects in a different way (# of users, for instance).
    public class MyClass implements Comparable
       String host;
       int    port;
       int    currNumUsers;
       Object someOtherObjectReferenceINeed;
       // or if the object reference you need is an Integer, make that last member
       // an int...
       // Also, let's keep a Comparator in here for comparing # of users.
       // See further down for actual implementation...
       public static final Comparator BY_NUM_USERS = new NumUsersComparator();
         // Use the equal methods to determine whether or not host and port matches
       public boolean equals( Object obj )
       // Use the compareTo method to compare 2 instances in terms of host and port
       public int compareTo( Object obj )
         // Make this object take care of changing # of users, outside of the
         // Comparable interface.
         public int getNumUsers();
         public int bumpNumUsers( int byThisAmount ); // changes # of users...
         // Beef up this object to take advantage of someOtherObjectReferenceINeed
    // Use this Comparator object to compare 2 instances of MyClass
    // according to # of users.
    public class NumUsersComparator implements Comparator
         public int compare( Object a, Object b )
              MyClass left      = (MyClass)a;
              MyClass right      = (MyClass)b;
              // I am assuming both # of users are of the same sign...positive
              return ( right.getNumUsers() - left.getNumUsers() );
    // Now when you need to compare, you can do it 2 different ways...
    // You can use whatever Collection you fits, List, Set, ...
    // I am going to use List in this case
    List gateways = new ArrayList;
    // add the objects...
    gateways.add( /* . . . */ );
    // Now let's sort in terms of user/port
    Collections.sort( gateways );
    // Let's sort in terms of number of users...
    Collections.sort( gateways, MyClass.BY_NUM_USERS );
    // I am going to mix them around now...
    Collections.shuffle( gateways );
    // Now let's find the gateway w/ the largest # of users...
    MyClass currMaxGateway = Collections.max( gateways, MyClass.BY_NUM_USERS );
    .

  • Sorting large amounts of data with treemap

    Hello. Im doing a project where I have to sort a large amount of data. The data is formed by a unique number and a location (a string).
    Something like this
    NUMBER .... CITY
    1000123 BOSTON
    1045333 HOUSTON
    5234222 PARIS
    2343345 PARIS
    6234332 SEATTLE
    I have to sort the data by location and then by unique number...
    I was using the TreeMap to do this : I used the location string as a key - since I wanted to sort the data by that field - but, because the location string is not unique, at the moment to insert the data on the TreeMap, it overwrites the object with the same location string, saving only the last one that was inserted.
    Is there any Collection that implements sorting in the way that I need it?... or if there isnt such thing... is there any collection that supports a duplicated key object???
    Thanks for your time!
    Regards
    Cesar

    ... or use a SortedSet for the list of numbers (as the associated value for
    the location key). Something like this:voidAddTuple(String location, Integer number) {
       SortedSet numbers= set.get(location);
       if (numbers == null)
          set.put(location, numbers= new TreeSet());
       numbers.put(number);
    }kind regards,
    Jos

  • Sorting with TreeMap vs. quicksort

    I've been sorting lists by throwing them into a TreeMap then retrieving them in order (especially for fairly evenly distributed lists of strings), thereby leveraging its binary tree characteristics.
    My belief is that sorting this way takes N log N time, just as quicksort (as in Arrays.sort) does -- because adding items to a TreeMap takes log N time -- without any danger of stack overflows from recursing on a huge list as with quicksort, and fewer method calls which can get expensive.
    I'm figuring that even if this way of sorting uses more memory than an in-place sort as in Arrays.sort, at least it won't overflow the stack, and will mostly be eligible for garbage collection anyway.
    Could someone correct or confirm my conclusions, reasoning or assumptions? And how well do they apply to Collections.sort's merge sort?

    Using a tree guarentees worst case O(n log n) for n
    inserts.Amazing, my untrained intuition was correct.
    As for stack problems these are unlikely to occur until
    logn is at least a few thousand (think about stupidly large values of
    n).I regularly need to sort lists of tends of thousands of strings.
    .. its [quicksort's] gotcha is that
    performance can degrade well below this approaching
    O(n^2) (might be higher. I cant remember).Yes, O(n^2) for adversarial data. Does mergesort require a shallower recursion than quicksort does?
    Since temporary use of the heap is rarely a concern for me, and datasets are very large, it sounds like mergesort and the TreeMap are viable contenders for preferred sorting methods. But I'm still apprehensive about mergesort's use of recursion.
    Thank you, I gave you 5 duke dollars and matei 2.

  • Collections problem - Sorting object (not key) in treemap

    Hello everyone,
    I don't know if TreeMap is the right thing for what I want to do, but I haven't found anything better yet. What I want to do is have a tree map like that
    index -- value (Double)
    1        500
    2        450
    3        500   (Multiple value)
    4        123so I used a TreeMap, but what I want to do is get the indexes with the highest 5 values for example. Should I still use TreeMap? Is there a simple way to keep the values sorted rather than the keys (indices)?
    Thanx

    My problem is though, I want to sort them but then get the index of the minimum for example and with the LinkedList, I lose the mapping. With the treemap, I also cannot get the key (index) given an object, only the other way round. Is there a way to handle this?

  • Sort on a TreeMap

    Hello,
    I'm trying to change the order of that SortedMap; instead ascending order I need it as descending order. Is it
    possible? It seems I can't call the 'sort' on a TreeMap but I don't see any other solution. thanks
    //I need a ordering on the Key Integer
    SortedMap <Integer, Vector< Word> > _freqToIndex = new TreeMap < Integer, Vector< Word > >();
    Comparator<Integer > comp = Collections.reverseOrder();
    Collections.sort( dic._freqToIndex.KeySet(), comp );

    mickey0 wrote:
    This arise an exception as well.
              SortedMap <Integer, Vector< Word> > ss = new TreeMap < Integer, Vector< Word > >( new Reversing() );
              //ss = dic._freqToIndex;
              ss.putAll( dic._freqToIndex );
    public class Comp implements Comparator<Integer >{
         public int compare(Integer i1, Integer i2) {
              return i2.compareTo( i1 );
    }(One more thing: I can't udnerstand how put that class inside another class; in fact I had to put Comp in a different file because the compiler wanted that!)There are various ways of doing this: one of them is as an anonymous inner class:
    import java.util.*;
    public class Main {
        public static void main(String[] args) {
            SortedMap<Integer, String> map = new TreeMap<Integer, String>(new Comparator<Integer>(){
                public int compare(Integer i1, Integer i2) {
                    return i2.compareTo(i1);
            map.put(1, "A");
            map.put(3, "C");
            map.put(2, "B");
            System.out.println(map);
    } As you can see, I used your implementation and it works just fine.

  • Custom Sorting in TreeMap.

    Can I sort the contents of TreeMap according to values.
    As default TreeMap is sorted according to Keys. But I want to sort it according to values. Can I met this using comparator?
    Thanks in advance for your help.

    no, you cannot. besides sorting, the comparator is used by the treemap to locate keys/values given an arbitrary key. if you sorted the map based on the values, you would never be able to find anything in it by key.

  • Sorting the TreeMap

    I am trying to sort a TreeMap based on Values like this:-
    public class SortedValueTest
    public static void main( String[] args )
    Map map = new TreeMap();
    map.put( "field1", new Integer( 0 ) );
    map.put( "field2", new Integer( 2 ) );
    map.put( "field3", new Integer( 2 ) );
    map.put( "field4", new Integer( 0 ) );
    Set set = new TreeSet(
    new Comparator()
    public int compare( Object o1, Object o2 )
    Map.Entry e1 = (Map.Entry)o1;
    Map.Entry e2 = (Map.Entry)o2;
    Integer d1 = (Integer)e1.getValue();
    Integer d2 = (Integer)e2.getValue();
    return d1.compareTo( d2 );
    set.addAll( map.entrySet() );
    for ( Iterator iter = set.iterator(); iter.hasNext(); )
    Map.Entry entry = (Map.Entry)iter.next();
    System.out.println( entry.getKey() + " = " + entry.getValue() );
    The output obtained is like this:-
    field1 = 0
    field2 = 2
    But the required output should not omit the duplicate items.
    So the above solution based on TreeSet does not seems to be applicable.
    Is there any alternative way to solve this problem?
    Thanks in Advance.

    SOLVED!!!
    import java.io.IOException;
    import java.util.*;
    * Created by IntelliJ IDEA.
    * User: ponmanadiyilv
    * Date: 06-Mar-2006
    * Time: 11:46:29
    * To change this template use File | Settings | File Templates.
    public class GoodSort {
    public static void main(String[] args) throws Exception {
    Map m = new HashMap();
    m.put ("field1", new Integer(12));
    m.put ("field2", new Integer(2));
    m.put ("field3", new Integer(30));
    m.put ("field4", new Integer(5555));
    m.put ("field5", new Integer(0));
    m.put ("field6", new Integer(5555));
    ArrayList outputList = sortMap(m);
    int count = 0;
    count = outputList.size();
    while(count > 0) {
    Map.Entry entry = (Map.Entry) outputList.get(--count);
    System.out.print("Key:" + entry.getKey());
    System.out.println("\tValue:" + entry.getValue());
    * This method will use Arrays.sort for sorting Map
    * @param map
    * @return outputList of Map.Entries
    public static ArrayList sortMap(Map map) {
    ArrayList outputList = null;
    int count = 0;
    Set set = null;
    Map.Entry[] entries = null;
    // Logic:
    // get a set from Map
    // Build a Map.Entry[] from set
    // Sort the list using Arrays.sort
    // Add the sorted Map.Entries into arrayList and return
    set = (Set) map.entrySet();
    Iterator iterator = set.iterator();
    entries = new Map.Entry[set.size()];
    while(iterator.hasNext()) {
    entries[count++] = (Map.Entry) iterator.next();
    // Sort the entries with your own comparator for the values:
    Arrays.sort(entries, new Comparator() {
    public int compareTo(Object lhs, Object rhs) {
    Map.Entry le = (Map.Entry)lhs;
    Map.Entry re = (Map.Entry)rhs;
    return ((Comparable)le.getValue()).compareTo((Comparable)re.getValue());
    public int compare(Object lhs, Object rhs) {
    Map.Entry le = (Map.Entry)lhs;
    Map.Entry re = (Map.Entry)rhs;
    return ((Comparable)le.getValue()).compareTo((Comparable)re.getValue());
    outputList = new ArrayList();
    for(int i = 0; i < entries.length; i++) {
    outputList.add(entries);
    return outputList;
    }//End of sortMap

  • Sort a treemap/hashmap by values

    I'm writing a really simple program that creates a treemap and writes it line by line to a text file. I want it to be ordered by the values asociated with the keys, not by the keys themselves.
    The map simply has strings for keys, the value with each one is the number of times that string appears in the input text file.
    I've looked at the constructor treemap(Comparator c), but didn't really see how I could use it. Is there a simple way to get the text file sorted by values, not the keys?
    Thanks!

    Do you really need a SortedMap to do this? Is there any point when you really need the data sorted by the String keys?
    Probably easier, once you have the collection of String/frequency pairs, just to dump that into a List and sort the List using a comparator that looks at the frequency primarily.

  • About sort Date in TreeMap

    import java.util.*;
    public class testTreeMap{
    public static void main(String[] args){
    TreeMap tree=new TreeMap();
    Calendar date=Calendar.getInstance();
    date.set(2004,9,7);
    tree.put(date,"a");
    date.set(2003,9,7);
    tree.put(date,"b");
    date.set(2002,9,7);
    tree.put(date,"c");
    date.set(2001,9,7);
    tree.put(date,"d");
    Set s=tree.keySet();
    Object[] objs=s.toArray();
    for(int i=0;i<objs.length;i++){
    Calendar b=(Calendar)objs;
    System.out.print(" "+b+" ");
    error Report
    Exception in thread "main" java.lang.ClassCastException: java.util.GregorianCale
    ndar
    at java.util.TreeMap.compare(Unknown Source)
    at java.util.TreeMap.put(Unknown Source)
    what's wrong?who can help me to correct this program?
    at testTreeMap.main(testTreeMap.java:10)

    what you need is like this:
    tree.put(date.getTime(),"xxx");Yes to be able to use a TreeMap the key must be a class which implements the Comparable interface and Date is such a class. Luckily it's possible to convert between Calendar and Date objects using the getTime/setTime pair of methods. So you can store Date objects in the TreeMap but work with Calendar objects outside.
    On the other hand if you don't need the ordering on key provided by a TreeMap you can as well store Calendar objects directly in a HashMap because accesses are faster.

  • Cannot sort child rows in multilevel tree table

    Hi,
    I originally hijacked a two-year-old forum thread that was vaguely similar to my issue, but a kind forum moderator split my post away
    (and deleted my other hijack post asking this same question)
    so that my inquiry might be viewable on its own.
    Hopefully someone can pay attention to my issue instead of getting it confused with those other old forum threads.
    So, here we go ...
    Is sorting in a treeTable at a particular level possible? Just want to let you I have tried the following approaches to do this. But it dis not work for me.
    I have tree table with 2 levels. I am trying to sort the child rows based on its column say "Display Sequence".
    User can type in number in this column which contains input text. On value change event of the this field, all the
    child rows in the level 2 need to be sorted. This needs to be done without committing the data. On commit it works,
    because it sorts based on order by clause. I want the child rows to be sorted on value change event. Following
    various approaches I tried.
    TreeModel tModel = (TreeModel)treeTable.getValue();
    SortCriterion sortCriterion = new SortCriterion("DisplaySequence",true);
    List<SortCriterion> sortCriteriaList = new ArrayList<SortCriterion>();
    sortCriteriaList.add(sortCriterion);
    tModel.setSortCriteria(sortCriteriaList);
    The above code does not work, As "DisplaySequence" is not available in the parent view object.
    Here is approach no 2
    JUCtrlHierBinding treeTableBinding = null;
    JUCtrlHierNodeBinding nodeBinding = null;
    JUCtrlHierNodeBinding parentNodeBinding = null;
    JUCtrlHierTypeBinding nodeHierTypeBinding = null;
    Key rowKey;
    Object dispSeqObj;
    Number displaySequence = null;
    Map<Key,Number> keyValueMap = null;
    Set<Key> emptyValueKeySet = null;
    Map<Key,Number> sortedKeyValueMap = null;
    DCIteratorBinding target = null;
    Iterator iter = null;
    int rowIndex = 1;
    RowSetIterator rsi = null;
    Row currentRow = null;
    Row row = null;
    RowKeySet selectedRowKey = lookupTreeTable.getSelectedRowKeys();
    Iterator rksIterator = selectedRowKey.iterator();
    if (rksIterator.hasNext()) {
    List key = (List)rksIterator.next();
    System.out.println("key :"+key);
    treeTableBinding = (JUCtrlHierBinding) ((CollectionModel)lookupTreeTable.getValue()).getWrappedData();
    nodeBinding = treeTableBinding.findNodeByKeyPath(key);
    parentNodeBinding = nodeBinding.getParent();
    //rsi = nodeBinding.getParentRowSetIterator();
    rsi = parentNodeBinding.getChildIteratorBinding().getRowSetIterator();
    keyValueMap = new LinkedHashMap<Key,Number>();
    emptyValueKeySet = new LinkedHashSet<Key>();
    // Gets the DisplaySequence by iterating through the child rows
    while(rsi.hasNext()) {
    if(rowIndex==1)
    row = rsi.first();
    else
    row = rsi.next();
    rowKey = row.getKey();
    dispSeqObj = row.getAttribute("DisplaySequence");
    if(dispSeqObj!=null && dispSeqObj instanceof Number) {
    displaySequence = (Number)dispSeqObj;
    keyValueMap.put(rowKey, displaySequence);
    }else {
    emptyValueKeySet.add(rowKey);
    rowIndex++;
    rowIndex = 0;
    // Sort the numbers using comparator
    DisplaySequenceComparator dispSeqComparator = new DisplaySequenceComparator(keyValueMap);
    sortedKeyValueMap = new TreeMap<Key,Number>(dispSeqComparator);
    sortedKeyValueMap.putAll(keyValueMap);
    rsi.reset();
    nodeHierTypeBinding = nodeBinding.getHierTypeBinding();
    System.out.println("nodeHierTypeBinding :"+nodeHierTypeBinding);
    String expr = nodeHierTypeBinding.getTargetIterator();
    if (expr != null) {
    Object val = nodeBinding.getBindingContainer().evaluateParameter(expr, false);
    if (val instanceof DCIteratorBinding) {
    target = ((DCIteratorBinding)val);
    ViewObject targetVo = target.getViewObject();
    System.out.println("targetVo :"+targetVo);
    targetVo.setAssociationConsistent(true);
    //ri = target.findRowsByKeyValues(new Key[]{rowData.getRowKey()});
    rsi = parentNodeBinding.getChildIteratorBinding().getRowSetIterator();
    //rsi = nodeBinding.getParentRowSetIterator();
    // Rearrange the tree rows by inserting at respective index based on sorting.
    ViewObject vo = nodeBinding.getViewObject();
    iter = sortedKeyValueMap.keySet().iterator();
    while(iter.hasNext()) {
    currentRow = rsi.getRow((Key)iter.next());
    rsi.setCurrentRow(currentRow);
    rsi.setCurrentRowAtRangeIndex(rowIndex);
    //rsi.insertRowAtRangeIndex(rowIndex, currentRow);
    rowIndex++;
    iter = emptyValueKeySet.iterator();
    while(iter.hasNext()) {
    currentRow = rsi.getRow((Key)iter.next());
    rsi.setCurrentRow(currentRow);
    rsi.setCurrentRowAtRangeIndex(rowIndex);
    //rsi.insertRowAtRangeIndex(rowIndex, currentRow);
    rowIndex++;
    rsi.closeRowSetIterator();
    AdfFacesContext.getCurrentInstance().addPartialTarget(treeTable);
    private class DisplaySequenceComparator implements Comparator {
    Map<Key,oracle.jbo.domain.Number> dispSeqMap = null;
    public DisplaySequenceComparator(Map<Key,oracle.jbo.domain.Number> dispSeqMap) {
    this.dispSeqMap = dispSeqMap;
    public int compare(Object a, Object b) {
    Key key1 = (Key)a;
    Key key2 = (Key)b;
    oracle.jbo.domain.Number value1 = dispSeqMap.get(key1);
    oracle.jbo.domain.Number value2 = dispSeqMap.get(key2);
    if(value1.getValue() > value2.getValue()) {
    return 1;
    } else if(value1.getValue() == value2.getValue()) {
    return 0;
    } else {
    return -1;
    In the above code I tried to perform sorting of DisplaySequence values using comparator, then tried to rearrange
    nodes or rows based on sort resurts. But rsi.insertRowAtRangeIndex(rowIndex, currentRow) give
    DeadViewException...unable to find view reference. While setting current row also does not work.
    Approach 3.
    DCIteratorBinding iter1 =
    bindings.findIteratorBinding("childIterator");
    iter1.executeQuery();
    SortCriteria sc = new SortCriteriaImpl("DisplaySequence",false);
    SortCriteria [] scArray = new SortCriteria[1];
    scArray[0] = sc;
    iter1.applySortCriteria(scArray);
    Any help in Sorting Child nodes ADF treeTable is appreciated. Thanks in Advance.
    Abhishek

    Hi Frank,
    Thanks for your reply. I have tried similar approach for sorting tree table child rows based on user specified number and it works. But there is a limitation for this. This sorting works only for read only/transient view object. For updatable view object after sorting, data cannot be saved or updated, as it cannot find the rowid. Here is what I tried
    In the ParentViewImpl class,
    1. overrode the method createViewLinkAccessorRS, so that this method is forcefully executed.
    @Override
    protected ViewRowSetImpl createViewLinkAccessorRS(AssociationDefImpl associationDefImpl,
    oracle.jbo.server.ViewObjectImpl viewObjectImpl,
    Row row,
    Object[] object) {
    ViewRowSetImpl viewRowSetImpl = super.createViewLinkAccessorRS(associationDefImpl, viewObjectImpl, row, object);
    return viewRowSetImpl;
    2. Added the following method, which will be invoked on valueChange of DisplaySequence in child row. Expose this method through client interface. This method accept a parameter i.e. parent row key of the child row.
    public void sortChildRecords(Key parentKey) {
    ViewObject viewObject = null;
    String type = null;
    if(parentKey==null) {
    Row [] row = this.findByKey(parentKey, 1);
    RowSet rowSet = (RowSet)row[0].getAttribute("ChildVO");
    viewObject = rowSet.getViewObject();
    viewObject.setSortBy("DisplaySequence asc");
    }else {
    Row row = getCurrentRow();
    RowSet rowSet = (RowSet)row.getAttribute("ChildVO");
    viewObject = rowSet.getViewObject();
    viewObject.setSortBy("DisplaySequence asc");
    this.setQueryMode(ViewObject.QUERY_MODE_SCAN_DATABASE_TABLES |
    ViewObject.QUERY_MODE_SCAN_ENTITY_ROWS);
    this.executeQuery();
    For custom sort, lets say all the numbers should be display first in ascending order, and null or empty values to be display at the end need to override the getRowComparator method in the ChildViewImpl class,
    Here is the code for the same
    @Override
    public Comparator getRowComparator() {
    SortCriteria sortCriteria = new SortCriteriaImpl("DisplaySequence",false);
    SortCriteria [] sortCriterias = new SortCriteria[1];
    sortCriterias[0] = sortCriteria;
    return new DisplaySequenceComparator(sortCriterias);
    private class DisplaySequenceComparator extends RowComparator {
    public DisplaySequenceComparator(SortCriteria [] sortCriterias) {
    super(sortCriterias);
    public int compareRows(Row row1, Row row2) {
    Object dispSeqObj1;
    Object dispSeqObj2;
    Number dispSeq1 = null;
    Number dispSeq2 = null;
    boolean compareRow1 = true;
    boolean compareRow2 = true;
    if(row1!=null) {
    dispSeqObj1 = row1.getAttribute("DisplaySequence");
    if(dispSeqObj1!=null && dispSeqObj1 instanceof Number) {
    dispSeq1 = (Number)dispSeqObj1;
    }else {
    compareRow1 = false;
    if(row2!=null) {
    dispSeqObj2 = row2.getAttribute("DisplaySequence");
    if(dispSeqObj2!=null && dispSeqObj2 instanceof Number) {
    dispSeq2 = (Number)dispSeqObj2;
    }else {
    compareRow2 = false;
    if(compareRow1 && compareRow2) {
    if(dispSeq1.getValue() > dispSeq2.getValue()) {
    return 1;
    } else if(dispSeq1.getValue() == dispSeq2.getValue()) {
    return 0;
    } else {
    return -1;
    if(!compareRow1 && compareRow2)
    return 1;
    if(compareRow1 && !compareRow2)
    return -1;
    return 0;
    The above solution works properly, and sorts the child tree rows. But while saving the changes, update fails. I also came to know that in-memory sorting is applicable to read-only/transient view objects from some blogs and also mentiond in this link http://docs.oracle.com/cd/E24382_01/web.1112/e16182/bcadvvo.htm
    Is there any way that updatable view objects can be sorted and saved as well?
    Thanks,
    Abhishek
    Edited by: 930857 on May 2, 2012 7:12 AM

Maybe you are looking for

  • Extended notification by email problems with htmlb:link

    Hi, Have problem with link using <htmlb:link id     ="action" reference= "<%= LINK_URL %>" > everything is fine till the END link is shown OK <a class="sapLnk" id="action" href="link" target="blank"> etc. but when i receive email link is with additio

  • In operator and subquery

    I have created a sql query for oracle rdbms. I am passing a particular id in the subquery of my main query . I have one major difference in the query whenever i use a subquery with IN operator and using IN_list values in IN operator. I found that whe

  • FICA: Cash desk

    Hi experts, I am facing the following scenario, several utilities companies under one holding. A customer of a company can pay his bills through the cash desk of any of the other companies of the holding. At posting area 0030 I can set the accounts f

  • ABout printer setting(SPAD) , especially Font setting.

    Hi, Experts. Now, I want to change Font setting. (Windows2000/R3 46C) There is difference between  "Host Spool Access Method :F " and "Host Spool Access Method :S ". Concretly, when I use "Method:F", it is printed by  "Mincho". But I use "Method:S",

  • Original TWAIN?

    If someone still has them, could you please give me the ORIGINAL 'TWAIN Source Manager.Shlb' file that's located in /System/Library/CFMSupport and/or the ORIGINAL 'TWAIN.framework' that's located in /System/Library/Frameworks These two files are brok