Sorting in List Hash Map

Hi All ,
I i have the data in below format:
Name     Age     Skill     Company
Vass     21     Java     Zylog
Samy     24     PB     HP
Lee     18     ADF     CTS
Reng     16     Java     Info
I converted this data into java collections List<Hash Map> like this.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
public class HashMapDemo {
    public static void main(String[] args) {
        // Create a hash map
        List<HashMap> list = new ArrayList<HashMap>();
        HashMap hm = new HashMap();
        hm.put("Name", new String("Vass"));
        hm.put("Age", new Integer(21));
        hm.put("Company", new String("Zylog"));
        hm.put("skill", new String("Java"));
        list.add(hm);
        HashMap hm1 = new HashMap();
        hm1.put("Name", new String("Samy"));
        hm1.put("Age", new Integer(24));
        hm1.put("Company", new String("HP"));
        hm1.put("skill", new String("PB"));
        list.add(hm1);
        HashMap hm2 = new HashMap();
        hm2.put("Name", new String("Lee"));
        hm2.put("Age", new Integer(18));
        hm2.put("Company", new String("CTS"));
        hm2.put("skill", new String("ADF"));
        list.add(hm2);
        HashMap hm3 = new HashMap();
        hm3.put("Name", new String("Reng"));
        hm3.put("Age", new Integer(16));
        hm3.put("Company", new String("Info"));
        hm3.put("skill", new String("Java"));
        list.add(hm3);
        Iterator i = list.iterator();
        while (i.hasNext()) {
            System.out.println(i.next());
} As per data (table format) i want to sort the data in Column level
how can i to achieve ?.
List<HashMap> is type of collection is help to me?
Any idea?
Thanks,
Vass Lee

Check out Comparator, and use Google to find examples on how to use it.
http://download.oracle.com/javase/6/docs/api/java/util/Comparator.html
Still sorting a collection of hashmaps is a bit odd design though. I think you want to create a simple class with properties in stead of a HashMap, then implement Comparable on that class.

Similar Messages

  • How to sor hash map

    Hi,
    [b] how to sort hash map contains integer objects,
    HashMap map=new HashMap();
    map.put("1",new Integer("1"));
    map.put("2",new Ineger("2")):
    map.put("3",new Ineger("3")):
    map.put(4,new Integer("4"));
    map.put("10",new Integer("10"));
    map.put("11",new Integer("11"));
    map.put("12",new Integer("12"));
    map.put("20",new Integer("20"));
    map.put(30,new Integer("30"));
    if i am using treemap
    TreeMap map1=new TreeMap(map);
    System.out.println(map1);
    answer is
    1 ,10,11,12,2,20,3,30,4
    but i am accepting the results
    1,2,3,4,10,11,12,20,30.
    what to do
    with regardsshannu sarma[/b]

    This is usual behaviour of a Map. You cannot sort a Set or Map. You can sort a List only using Collections.sort().
    If you want to use a Map which adds all elements according to the order you've added it, then use LinkedHashMap.
    And if you want to capture the keys, use Map.values() which returns an ordered Collection (and after converting it to List, you can sort it).
    Another approach is to create a wrapper object and put it in a List. Then you can use the java.util.Comparator to sort objects in a List.

  • Is it possible to insert a value in a hash map at a perticular index ?

    Hello Techies,
    I have a drop down list which is used to select a contry name. I also contains " All " option which is used to select all countries.
    I am using HashMap for this drop down list for getting corresponding value.
    Now, my requirement is the " All " should display as the first in the drop down list. Hash map didn't support bcoz it is in sorted order,
    Can any one help me with alternative solution ?
    Thanks in advance.
    Javed

    Now, my requirement is the " All " should display as the first in the drop down
    list. Hash map didn't support bcoz it is in sorted order,Rather HashMap doesn't support this because according to the first paragraph
    of its API documentation "This class makes no guarantees as to the order of the
    map; in particular, it does not guarantee that the order will remain constant over
    time".
    Is the drop down list a JComboBox? If so how are you using the hash map?
    And can't you just create an array from the hash map's keys, putting "All" at the
    start?

  • "Economizing" in a list of maps with identical keys (like a database table)

    Hi there!:
    I've been checking this forum for information about something like what I state in the title of this message, but haven't found such a specific case. I'm commenting my doubt below.
    I'm working with a list of maps whose keys are exactly the same in all them (they're of type String). Indeed it could be considered an extrapolation of a database table: The list contains maps which act as rows, and every map contains keys and values which represent column names and values.
    However, this means to repeat the same key values on every map and this spends memory. Right, maybe it's not such a big spent, but since the list can contains thousands of maps, I think that it would be better to choose a more "economical" way to achieve the same result.
    I had thought about building a class which stored everything as a list of lists and, internally, it mapped that String keys with the corresponding Integer indexes of every list. But then I realized that maybe I was re-inventing the wheel, because it's very probable that someone has already made that. Maybe is there a class on the Core API which allows that?
    Thank you very much for your help.

    Well, after re-reading the Java tutorial which is located in the Sun website I've came to a conclusion which I should have before, when I thought about using StringBuffers as keys of the maps instead of Strings.
    I'm so used to build Strings using literals instead of the "new String ()" constructor (just as everyone) that I had forgotten that, as it happens with any kind of object but not the primary data types, Strings are not passed to the methods by value, but by reference. The fact of them being immutable made me think that they were passed by value.
    Apart of that, my problem also was that using literals I was creating different String objects every time, despite the fact that they were equal about their content (making 400 different keys called "name" for example)
    In other words, I was doing something like this:
    // It makes a list of maps which will contain maps of boy's personal data (as if they were "rows" in a table).
    List <Map <String, Object>> listData = new ArrayList <Map <String, Object>> (listBoy.size ());
    // It loops over a list of Boy objects, obtained using EJB.
    for (Boy boy : listBoy) {
         // It makes a new map containing only the information which I'm interested on from the Boy object.
         Map <String, Object> map = new HashMap <String, Object> (2);
         map.put ("name", boy.getName ());
         map.put ("surname", boy.getSurname ());
         // It adds the map to the list of data.
         listData.add (map);
    }Well, the "problem" here (being too demanding, but I'm :P ) is that I was adding all the time new Strings objects as keys in every map. The key "name" in the first map was different from "name" in the second one and so on.
    I guess that my knowledge got messed at certain point and thought that it was impossible to use exactly the same String object in different maps (the reference, not the same value!). Thus, my idea of using StringBuffers instead.
    But thinking about it carefully, Why not to do this?:
    List <Map <String, Object>> listData = new ArrayList <Map <String, Object>> (listBoy.size ());
    // It makes the necessary String keys previously, instead of using literals on every loop later.
    String name = "name";
    String surname = "surname";
    for (Boy boy : listBoy) {
         // It uses references (pointers) to the same String keys, instead of new ones every time.
         Map <String, Object> map = new HashMap <String, Object> (2);
         map.put (name, boy.getName ());
         map.put (surname, boy.getSurname ());
         listData.add (map);
    }Unfortunately, the "hasCode" method on String is overloaded and instead of returning the typical hash code based on the single ID of the object in memory, it returns one based on its content. That way I can't make sure that the "name" key in one map refers to the same object in memory than another one. I know, I know. The common sense and the Java documentation confirm that, but had loved having an empiric way to demonstrate it.
    I guess that using "javap" and disassembling the generated bytecode is the only way to make sure that it's that way.
    I believe that it's solved now :) (if no one tells me the contrary). I still am mad at myself for thinking that Strings were passed by value. Thinking about it now it had no sense!
    dannyyates: It's curious because re-reading every answer I think that you maybe were pointing to this solution already. But the sentence "you put the +same+ string" was a little ambiguous for me and thought that you meant putting the same String as "putting the same text" (which I already was doing), not the same object reference (in other words, using a common variable). I wish we could have continued discussing that in depth. Thanks a lot for your help anyway :) .

  • How to create a dicitionary using hash map.

    Hi All,
    I want to create a dictionary using hash map where in i can add new words and there meaning. I have written some code But I am not happy with this. Can you suggest me how to add the words and there meanings to the hash map.
    I am not able to add the words and there meaning to the hash map.
    for this i tried creating a dictionary class.
    // Using hashmap
    import java.util.*;
    public class Dictionary
        public static void main(String[] args)
            // Create a hash map
            HashMap hm = new HashMap();
            // put elements to the map
            hm.put("Abode: ", "Home");
            hm.put("Balance: ", "An intrument to measure or weigh");
            hm.put("Car: ", "Automobile");
            hm.put("Dinner: ","Last meal of the day generally had after evening and before sleeping");
            hm.put("Embossed: ", "Engraved kind");
            Set set = hm.entrySet();
            Iterator i = set.iterator();
            while (i.hasNext())
                Map.Entry me = (Map.Entry) i.next();
                System.out.print(me.getKey() + ": ");
                System.out.println(me.getValue());
            System.out.println();
    }This is the other Dictionary class which i created.
    public class Main_Dictionary
        public static void main(String[] args)
            Content_Dictionary cd = new Content_Dictionary();
            cd.getContent_Dictionary("Abode", "Home");
            cd.displayValues();
    class Content_Dictionary
        String word, meaning;
        Content_Dictionary()
            word = "a";
            meaning = "b";
        Content_Dictionary(String x, String y)
            word = x;
            meaning = y;
        void getContent_Dictionary(String w, String m)
            word = w;
            meaning = m;
        void displayValues()
            System.out.print(word + ": ");
            System.out.println(meaning);
    }If i create an interface containing all the words and there meaning
    public interface Words_Dictionary
        String Abode = "Home";
        String Dark = "Lacking brightness";
        String Balance = "An intrument to measure or weigh";
        String Car = "Type of Automobile";
        String Dinner = "Last meal of the day";
        String Embossed  = "Engraved kind";
        String Adroit = "SkillFul";
    }and then create a another class which implements this interface, but how should i add these words and there meaning in the hashmap.

    I tried creating word document but i was unable to
    figure out how to do the operations on the word
    document and its content,
    So This is what i could come up with, i just created
    one class Dictionary , now I am able to search for
    the meaning of the word specified by me, and I am
    able to print all the words and there meanings added
    to the hashmap, but i am not able to figure out how
    to add a new word and the meaning in the hashmap and
    how to find is a word is there or not...May I suggest a slightly different approach?
    Do not create a String ==> String mapping, but a String ==> List<String> mapping. And do NOT place everything inside your main method.
    Here's a small demo:
    import java.util.ArrayList;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.List;
    public class Dictionary {
        private Map< String, List<String >> dictionary;
        public Dictionary() {
            dictionary = new HashMap< String, List<String >>();
        public void addWord(String base, String meaning) {
            List<String> allMeanings = dictionary.get(base);
            if(allMeanings == null) { // if null, there is no entry mapped to 'base' yet: create a new one
                List<String> newMeanings = new ArrayList<String>();
                newMeanings.add(meaning);
                dictionary.put(base, newMeanings);
            } else {
                allMeanings.add(meaning);
        public List<String> search(String base) {
            // your code here
            return null;
        // ... other methods ...
        public String toString() {
            StringBuilder strb = new StringBuilder();
            for(Map.Entry< String, List<String >> e : dictionary.entrySet()) {
                strb.append(e.getKey());
                strb.append(" : ");
                strb.append(e.getValue());
                strb.append('\n');
            return strb.toString();
        public static void main(String[] args) {
            Dictionary dict = new Dictionary();
            dict.addWord("Abode", "Home");
            dict.addWord("Abode", "House");
            dict.addWord("Car", "Automobile");
            dict.addWord("Car", "Vehicle");
            System.out.println(dict);
    }Good luck.

  • List to Map

    Hi
    I have code:
    Map a = new HashMap();
            for(int k=0;k<lis.size();k++){
             a.put(lis.get(k)[0], lis.get(k)[1]);
             System.out.println("L:"+lis.get(k)[0]+"\nm:"+a);
            }and lis is
      ArrayList<Object[]> lis = new ArrayList();out is:
    L:siedziba
    m:{siedziba=qq}
    L:data
    m:{data=2008-04-03, siedziba=qq}
    L:regon
    m:{regon=123456789, data=2008-04-03, siedziba=qq}
    L:ekd
    m:{ekd=7411, regon=123456789, data=2008-04-03, siedziba=qq}
    L:nipp
    m:{ekd=7411, regon=123456789, data=2008-04-03, nipp=, siedziba=qq}
    L:peselp
    m:{ekd=7411, peselp=, regon=123456789, data=2008-04-03, nipp=, siedziba=qq}
    How put Object to Map that new Object insert on last position on Map ??
    (example:
    wrong:
    m:{ekd=7411, peselp=, regon=123456789, data=2008-04-03, nipp=, siedziba=qq}
    correctly:
    m:{ siedziba=qq, data=2008-04-03, regon=123456789,ekd=7411, nipp=, peselp=}
    Or how to set Set.iterator to get value Object from Map in the same order as in List ??
    PS.
    Sorry for my bad english :)

    LRMK wrote:
    Order of objects in the map depends on its implementation. Hash map does not have make any promises on order. To my understanding there is no map implementation that keep the insertion order in tact. So you cant do this unless you implement something on your ownLinkedHashMap does

  • While loop in a Hash Map

    My while loop doesnt seem to work in a hash map, it works fine when I loop an array list.
    It compiles but it doesnt seem to find any employees, should I use another loop?
    {code
    public Employee find(String id)
    Employee foundEmployee = null;
    int index = 0;
    boolean found = false;
    while(index < register.size() && !found){
    Employee right = register.get(index);
    String namn = right.getName();
    if (namn.equals(id)){
    foundEmployee = right;
    found = true;
    index++;
    return foundEmployee;

A: while loop in a Hash Map

what if you looped on the key set?
  public Employee find(String id)
    Employee foundEmployee = null;
    Set<Integer> keySet = register.keySet();
    for (Integer key : keySet)
      Employee right = register.get(key);
      if (right.getName().equals(id))
        foundEmployee = right;
        break;
    return foundEmployee;
  }

what if you looped on the key set?
  public Employee find(String id)
    Employee foundEmployee = null;
    Set<Integer> keySet = register.keySet();
    for (Integer key : keySet)
      Employee right = register.get(key);
      if (right.getName().equals(id))
        foundEmployee = right;
        break;
    return foundEmployee;
  }

  • Using Hash maps

    Hi
    Just a quick one
    I have two hash maps - each containing information on the location of characters in a individual string.
    Is there some sort of method that allows me to compare the two maps and return the string locations where they contain the same information ?

    Hi evett,
    You might want to check out the method "entrySet()" in the Map class, once you get the 2 Set's, you can then use the "retainAll()" method of a Set to only keep the information that is the same in both Set's (which contains the information you want).
    Good Luck,
    Bud

  • Open a SharePoint List item in Modal Pop up in SP 2013 fails after you filter or sort the list

    Sorry for the long post. This has been killing me. I had this script working perfectly fine in SharePoint 2010 (online) and basically i have a source custom list (list A) with a hyperlink column and a Destination List with say title and my name.
    Source List (list A) looks like this with these 2 columns
    Title    Test Link
    A         Link 1
    B         Link 2 
    C         Link 3
    Each of these links link to the actual list item in the destination list, so for example, link 1 is/sites/2013DevSite/Lists/Destination%20List/EditForm.aspx?ID=1
    So basically i want anytime the Link are clicked that point to another list's item to open in a modal dialog and the script below worked perfectly fine in SharePoint 2010 (online)
    <script language="javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
    <script language ="javascript" type="text/javascript">   
    jQuery(document).ready(function() {
    jQuery('a[href*="EditForm.aspx"]').each(function (i, e) {
    // Store the A tag's current href in a variable
    var currentHref = jQuery(e).attr('href');
    jQuery(e).attr({
    'href': 'javascript:void(0);', 
    // Use the stored href as argument for the ShowInModal functions parameter.
    'onclick': 'ShowInModal("' + currentHref + '");'
    function ShowInModal(href) {
    SP.UI.ModalDialog.showModalDialog({title: "Edit Item", url: href});    
    </script>
    All it does is find the href tags for that particular value Editform.aspx and the pop modal works in SP 2010 online. So the site page is designed in such a way there is a content editor web part with the reference to this javascript file and the sharepoint
    list is right beneath it and this worked perfectly opening in modal windows in SP 2010.
    Since migration to 2013, this is what exactly happens
    1.) when you come to the site page, the modal works,
    2.) If you filter or sort on say the Title or Test Link column in Source list (lets say you select the Value A), the script does not fire at all, if i hover over the hyperlink, the who hyperlink is shown and does not open the hyperlink in the modal pop up.
    - This is important because i want to be able to sort on a particular item...
    Could someone please let me know what am i doing wrong and why is this not working when i sort the list. Thanks for all the help.
    Once again i am trying to open a sharepoint list item in Sharepoint 2013 from another list using Jquery

    A ListItem has its own unique row id so in all likelihood, an insert with the same data will result in a new list entry. The Lists Web Service however, has an UpdateListItem method which will take an update request. [refer
    http://msdn.microsoft.com/en-us/library/office/websvclists.lists.updatelistitems(v=office.15).aspx ]
    There is another note in the conference (marked answered) to your List Item Update problem. Probably worth a try too. [refer
    http://social.msdn.microsoft.com/Forums/en-US/bee8f6c6-3259-4764-bafa-6689f5fd6ec9/how-to-update-an-existing-item-in-a-sharepoint-list-using-the-wss-adapter-for-biztalk?forum=biztalkgeneral ]
    Regards.

  • Help with using mergesort to sort a list of names alphabetically?

    Hi, I'm trying to sort a list of names alphabetically, case-insensitive by using the mergesort technique.
    I wrote this code and when I trace it through on paper with an example array of names, it should work, but when I run it with an actual txt file, it's not correctly alphabetical.
    I'd appreciate it if someone could take a look at my code and give me some ideas on what my problem might be.
    Thanks in advance! (note: I also posted this question to java-forums.org, as I've been working on this little problem for over five hours and am in desperate need of some help!)
    public static void mergeSort(String[] names) 
            if (names.length >= 2) 
                String[] left = new String[names.length/2]; 
                String[] right = new String[names.length-names.length/2]; 
                for (int i = 0; i < left.length; i++) 
                    left[i] = names;
    for (int i = 0; i < right.length; i++)
    right[i] = names[i + names.length/2];
    mergeSort(left);
    mergeSort(right);
    merge(names, left, right);
    // pre : result is empty; list1 is sorted; list2 is sorted
    // post: result contains result of merging sorted lists;
    // add merge method below
    public static void merge(String[] names, String[] left, String[] right)
    int i1 = 0;
    int i2 = 0;
    for (int i = 0; i < names.length; i++)
    if (i2 >= right.length || (i1 < left.length && left[i1].compareToIgnoreCase(right[i1])<0))
    names[i] = left[i1];
    i1++;
    } else
    names[i] = right[i2];
    i2++;

    Welcome to the forum.
    Please read this to learn hot to format your code (and other things relevant for this forum):
    https://forums.oracle.com/forums/ann.jspa?annID=1535
    923566 wrote:
    Hi, I'm trying to sort a list of names alphabetically, case-insensitive by using the mergesort technique.
    I wrote this codeDo you know the <tt>TreeSet</tt> class?
    http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html
    With that sorting Strings is a two liner:
    http://www.java2s.com/Code/Java/Collections-Data-Structure/TreeSetDemo.htm
    bye
    TPD

  • Project 2013 - How do you sort the list of Enterprise Templates in Project Pro?

    In Project Pro 2013, click File > New > Enterprise I see the list of templates from our project server. We have a global installation with 40-50 templates. These are displayed in a random order and reading through the whole list to find the one I
    want is quite tedious. Is there a way to sort this list alphabetically? Can the list be displayed as a "details" view rather than icons?

    Greg --
    Guillaume is totally correct.  The display order of enterprise templates is by the date they were created.  I have tested this on a Project Server 2013 system that has the latest Cumulative Updates applied.  The problem is that in the
    Microsoft Project 2013 desktop application, Microsoft has ditched the Templates dialog we used to see and replaced it with a page in the Backstage.  I am afraid that in doing so, they have eliminated the sorting capabilities that we found in earlier versions.
    Out of curiosity, I have sent an e-mail to my MPV contacts within the Microsoft Project Server development team at Microsoft, asking if there is any intention of changing this functionality to allow for sorting by template name.  If I get an answer,
    I will post it in this user forum.
    Your question is a good one, and the sorting problem (or lack of sorting) can be a real problem in any organization that has a sizable number of enterprise templates.  Hope this additional bit helps.
    Dale A. Howard [MVP]

  • SORT NODE Fn. in Mapping

    Hello,
    I am trying to use this node fn sort in my gui mapping and whenever i use this fn and execute my mapping shows error:
    RuntimeException in Message-Mapping transformation: Exception:[java.lang.IllegalArgumentException: Unknown comparator type: Lexicografical] in class com.sap.aii.mappingtool.flib3.NodeFunctions method sort[com.sap.aii.mappingtool.flib3.Plainer@9a64eb0]
    Have any of you experienced such a situation?

    Hi
    check this thread,
    Message Mapping - Dump
    it maybe a different error, but it guides u in the right direction to analyse the problem.
    Sameer

  • Sorting a List on Parent Child Relationship

    I have to sort a list on Parent Child relation
    say
    I have a following list
    Object(Id,ParentId,.........)
    obj1(1,1,........);
    obj2(2,1,........);
    obj3(3,3,........);
    obj4(4,1,........);
    obj5(5,3,........);
    obj6(6,1,........);
    obj7(7,3,........);
    obj8(8,4,........);
    Logic is such that
    If Id and Parent Id is same then It is Parent Record
    I want the Result like
    obj1(1,1,........);
    obj2(2,1,........);
    obj4(4,1,........);
    obj6(6,1,........);
    obj3(3,3,........);
    obj5(5,3,........);
    obj7(7,3,........);
    obj8(8,4,........);
    Suggect Some Logic...............
    Thanks in advance.............

    sAsho wrote:
    That's the question how to do that?????????????????????????One question mark is sufficient. If you're going to go out of your way to write like an idiot, people won't take you seriously.
    "How do I do that?" is way to broad a question. You need to do some research, take your best shot, and post a specific question about the specific parts that are giving you trouble.
    Suggest something. I did suggest something.
    I suggested what you should google for to get you started. Just like writing clearly and intelligently, if you can't be bothered to read what people suggest and put in the effort to follow that suggestion and do your own research, you'll find people will quickly lose interest in trying to help you.
    Now I am additionally suggesting that you 1) pay closer attention and 2) do your own research.
    Recurcive sort kind of a think.................No idea what you're saying here. See my first point in this reply.

  • Sorting the list of value like in BEX but out of crystal report

    All,
    I have created a crystal report base on a BEX query where I have a variable for which  i am filtering base on a field period.fiscalyear.
    for the list of values that prompt you for this variable ...
    l in BEX we can do the sort by either alphabetical ascending order or descending alphabetical order such as:
    here is for ascending
    001.2008
    001.2009
    or by clicking on it we can do the following: (descending)
    012.2009
    012.2009
    however in crystal when refreshing the report in infoview it sorts the list of value base on the month
    something like this :
    JAN 2008 [0FISCPER].[K42008001]
    FEB 2008 [0FISCPER].[K42008002]
    We would like to have in crystal the same behaviour than in BEX,  so in crystal we would like to be able to get the list of values sorted in either ascending order to descending order. is there a way to do so ?
    notes also that we would like to avoid to create the variable in crystal
    Philippe

    Hi,
    in Crystal Reports you have per InfoObject - depending on the definition - the key value, the description and the member unique name. In BW these objects are defined as NUMC in most cases - which means it is a character / string.
    In your example the value is 001.2008 and 001.2009. What you can do in Crystal Reports is to split up the values into year and month and then sort based on the actual numbers.
    Ingo

  • Is it possible to sort the list of Conditions/Calculations?

    Is it possible to sort the list of Conditions/Calculations so that they display alphabetically in the list?
    My list of conditions is getting quite long and haphazard now!
    Cheers
    Sapphie

    I was afraid of that!. It is very disappointing because , as I am developing a set of reports for the first time, I will create conditions/calculations in quite a non-ordered way and then end up wanting to group similar ones together.
    Hopefully a future version will allow this?
    Lee

  • Maybe you are looking for