Sort ArrayList

I have a problem while sort the List<Map> .
Please tell me how do i sort this type of data by using predefined sort procedured i.e sotedSet, sortedMap.
Thanks in advance............

Collections.sort(theList, a Comparator)
Implement the Comparator the way you want.

Similar Messages

  • Sorting ArrayList multiple times on Multiple Criteria

    I have an arraylist that is sorted with Collection.sort() calling the ComparTo() included below. CompareTo sorts the file on totalLaps, totalSeconds, and etc.. The question is how do I change the sort criteria later in my process so that the arraylist is sorted on sequence number (the first field and a long number)? The only way I can currently think of doing it is to copy the array and create a separate class file like RaceDetail2 that implements a different CompareTo. To me that seems ridiculous!
    I've self tought myself Java using the online tutorials and a few books so sometimes I find I have some basic gaps in knowledge about the language. What am I missing? Seems like it should be simple.
    private ArrayList detailsArrayList = new ArrayList( );
    // Sort arraylist using compareTo method in RaceDetail file
    Collections.sort(detailsArrayList);
    public class RaceDetail implements Comparable, Cloneable {
         public RaceDetail( long seqNum, String boatNumText, int lapNum, String penalty, String question, long seconds, int totalLaps, long totalSecs, long lastSeqNum, long avg, long interval )
    public int compareTo( Object o )
         RaceDetail rd = (RaceDetail) o;
         int lastCmp = (totalLaps < rd.totalLaps ? -1: (totalLaps == rd.totalLaps ? 0: 1));
         int lastCmpA = boatNumText.compareTo(rd.boatNumText);
         int lastCmpB = (lapNum < rd.lapNum ? -1: (lapNum == rd.lapNum ? 0 : 1 ));
         int lastCmpC = (totalSecs < rd.totalSecs ? -1 : (totalSecs == rd.totalSecs ? 0 : 1 ));
         int lastCmpD = (seqNum < rd.seqNum ? -1 : (seqNum == rd.seqNum ? 0 : 1 ));
         int lastCmpE = (seconds < rd.seconds ? -1 : (seconds == rd.seconds ? 0 : 1 ));
         int lastCmpF = (lastSeqNum < rd.lastSeqNum ? -1 : (lastSeqNum == rd.lastSeqNum ? 0 : 1 ));
         // TotalLaps - Descending, TotalSeconds - ascending, lastSeqNum - ascending
         // Boat - Ascending, Second - ascending, seqNum - ascending
         return (lastCmp !=0 ? -lastCmp :
              (lastCmpC !=0 ? lastCmpC :
                   (lastCmpF !=0 ? lastCmpF :
                        (lastCmpA !=0 ? lastCmpA :
                             (lastCmpE !=0 ? lastCmpE :
                                  lastCmpD)))));
    }

    Thanks talden, adding the comparator below in my main program flow worked and now the arraylist sorts correctly. A couple of additional questions. I tried to place this in my RaceDetail class file and received a compile error so placed it in the main program flow and it worked fine. For organization, I would like to place all my sort routines together. Is there some trick to calling this method if I place it in my RaceDetail? Am I even allowed to do that?
    dhall - just to give you a laugh, this arraylist populates a JTable, uses a TableModel, and the TableSorter from the tutorial. Sorting works great in the JTable. Problem is I have to sort the arraylist a couple of times to calculate some of the fields such as lap times and total laps. I went through the TableSorter 5 or 6 times and never could figure out how to adapt it for what I wanted to do. So here I am using an example in my program and can't interpret it.
    Collections.sort( detailsArrayListLeft, SORT_BY_SEQUENCE );
    static final Comparator SORT_BY_SEQUENCE = new Comparator() {
    public int compare ( Object o1, Object o2 )
         RaceDetail rd1 = (RaceDetail) o1;
         RaceDetail rd2 = (RaceDetail) o2;
         return (rd1.seqNum() < rd2.seqNum() ? -1 : (rd1.seqNum() == rd2.seqNum() ? 0 : 1 ));

  • Sorting ArrayList

    Hi to all,
    I have to sort ArrayList elements in alphabetical order.When i tried to do with the following code iam getting "java.lang.ClassCastException:".
    List lStyleArray = new ArrayList();
    lStyleArray =(ArrayList)xxx.getxxx();
    Collections.sort(lStyleArray );
    Could anybody help to overcome this problem.Thanks in advance

    Presumably, "xxx.getxxx()" is returning something that is not an ArrayList.
    So you have to fix that, or change what you're trying to do. Maybe it's a List other than an ArrayList. You don't need to cast it to be an ArrayList specifically, probably.
    Also are you aware that on the first line, you're creating an ArrayList and then immediately throwing it away?

  • Sort ArrayList of objects by  id

    I have ArrayList of containing 'MonthlySale' objects, below is my class.
    import java.io.Serializable;
    import java.util.ArrayList;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import org.hibernate.annotations.GenericGenerator;
    @Entity
    @Table(name="Month")
    public class MonthlySale extends AuraDB implements Serializable, Comparable {
        private String quantity;
        private String value;
        private String avUnit;
        private int saleNumber;
        private int id;
        private String month;
        private String saleYear;
        private String description;
        private int reportNumber;
        public MonthlySale() {
        public MonthlySale(int saleNumber, String saleYear) {
            this.saleNumber = saleNumber;
            this.saleYear = saleYear;
        public MonthlySale(int saleNumber, String saleYear, int reportNumber) {
            this.saleNumber = saleNumber;
            this.saleYear = saleYear;
            this.reportNumber = reportNumber;
        @Column(name="AV_UNIT")
        public String getAvUnit() {
            return avUnit;
        public void setAvUnit(String avUnit) {
            this.avUnit = avUnit;
        @Column(name="MONTH")
        public String getMonth() {
            return month;
        public void setMonth(String month) {
            this.month = month;
        @Column(name="QUANTITY")
        public String getQuantity() {
            return quantity;
        public void setQuantity(String quantity) {
            this.quantity = quantity;
        @Column(name="SALES_NO")
        public int getSaleNumber() {
            return saleNumber;
        public void setSaleNumber(int saleNumber) {
            this.saleNumber = saleNumber;
        @Column(name="SALES_YEAR")
        public String getSaleYear() {
            return saleYear;
        public void setSaleYear(String saleYear) {
            this.saleYear = saleYear;
        @Column(name="VALUE")
        public String getValue() {
            return value;
        public void setValue(String value) {
            this.value = value;
        @Id
        @GenericGenerator(name="generator", strategy="increment")
        @GeneratedValue(generator="generator")
        @Column(name="ID")
        public int getId() {
            return id;
        public void setId(int id) {
            this.id = id;
        @Column(name="DESCRIPTION")
        public String getDescription() {
            return description;
        public void setDescription(String description) {
            this.description = description;
        @Column(name="REPORT_ID")
        public int getReportNumber() {
            return reportNumber;
        public void setReportNumber(int reportNumber) {
            this.reportNumber = reportNumber;
         public void selectMonthList() {
            hibSelectAll(this, "SELECT DISTINCT month FROM MonthlySale WHERE sales_year='" + saleYear + "' AND " +
                    " sales_no = '" + saleNumber + "'");
    }I want my arraylist to be ordered by id. I used collection.sort(), but i cannot sort by id.
    I get objects arrayList like this way
                monthlySale = new MonthlySale(Integer.parseInt(sales_no), sales_year, 0);
                monthlySale.selectMonthList();Any help appreciated.
    regards,
    Dil.

    Of course yes i did, like this.
    public int compareTo(Object o) {
           if(this.id == ((MonthlySale)o).getId()){
                return 0;
           }else if(this.id > ((MonthlySale)o).getId()){
                return 1;
           }else{
                return -1;
        }I implement 'MonthlySale class' form Comparable interface and override above method but it doesn't work.

  • How to Sort ArrayList

    Hi
    I have class like below , i store them in a ArrayList, is it possible to sort this ArrayList by name or by date.
    The class is as below
    public class MyInfo
    private String name;
    private Date date;
    //have getters and setters for name and date
    ArrayList data = new ArrayList();
    data.add(instance of MyInfo)
    Ashish

    Comparable doesn't really apply here IMO, since he
    uses different ordering criteria - name and date.Did you read the link? The tutorial contains useful information on the Comparator as well as the Comparable interface, which is why I posted it. I believe you're objecting only to the title of the article.
    :o)

  • Sort ArrayList by length

    I need to remove the string(s) with the least number of letters from an ArrayList.
    How can I sort the ArrayList by the length of the strings contained in it?

    Why would you need to?
    1.5 (you should be using an ArrayList<String>)
    list.get(i).length();Earlier (without generics)
    ((String)list.get(i)).length();This is of course irrelevent to impelementing a
    simple Comparator and passing it to Collections.Or
    list.get(i).toString().length();
    Or
    new StringBuilder(list.get(i).toString().toCharArray()).toString();

  • Sort ArrayList of HashMaps

    Hello all
    I have Arraylist that contains HashMaps
    how can I sort the ArrayList by some value of HashMaps?
    e.g. I have following HashMaps that are put inside a list and need to sort them by there value
    ArrayList<HashMap> al = new ArrayList<HashMap>();
    HashMap map1 = new HashMap();
    map1.add( new Integer( 2 ), "two" );
    map1.add( new Integer( 4 ), "four" );
    HashMap map2 = new HashMap();
    map2.add( new Integer( 22 ), "two2" );
    map2.add( new Integer( 42 ), "four2" );
    HashMap map3 = new HashMap();
    map3.add( new Integer( 23 ), "two" );
    map3.add( new Integer( 43 ), "four" );
    al.add(map1);
    al.add(map2);
    al.add(map3);Thanks

    Create a Comparator<HashMap> and pass that to Collections.sort. Write the comparator to use whatever rules you need to determine whether a map is "less than" another.
    http://java.sun.com/javase/6/docs/api/java/util/Comparator.html
    http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List, java.util.Comparator)
    http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html
    http://www.javaworld.com/javaworld/jw-12-2002/jw-1227-sort.html

  • Collecstions.sort(ArrayList) - Please Explain

    Hello,
    This is a rewrite of an earlier question. Hopefully, I better formed the question in this post.
    Can anyone explain why the first code example requires that I write a compareTo() method (called by Collections.sort(bidList)) and a toString() method (called by System.out.println(bidList), while the second code example requires no such additional code in my program?
    Thanks for all responses.
    Karl
    First Code Example (Requires comparTo() and toString() methods in the program.)
         public static void main(String[] args) {
            // fill a list with 5 bids
            ArrayList bidList = new ArrayList();
            for(int i=0; i<5; i++){
                //generate random number 0-100 for a bid amount
                bidList.add(new AuctionBid("Bidder" + i, (int)(Math.random()*100)));
            //sort the bids in natural order and display them
            Collections.sort(bidList); //Why does this call method compareTo()
            System.out.println("Natural order sort by bid amount");
            System.out.println(bidList); //Why does this call method toString()
    }Second Code Example (Does not require compareTo() or toString() methods in the program.)
            public static void main(String[] args) {
            // fill a list with 5 bids
            System.out.println("Printing bidList from Array: ");
            String[] bidList = new String[5]; 
            for(int i=0; i<5; i++){
                if(i==0){bidList[i] = "Zoey";}
                else if (i==1){bidList[i] = "Megan";}
                 else if (i==2){bidList[i] = "Larrry";}
                  else if (i==3){bidList[i] = "Brian";}
                   else if (i==4){bidList[i] = "Abigail";}
       List list2 = Arrays.asList(bidList); // Does NOT requre a toString() method to be coded.
       System.out.println("Printing Unsorted list2: ");
       System.out.println(list2);
       Collections.sort(list2); // Does NOT require a compareTo() method to be coded.
       System.out.println("Printing Sorted list2: ");
       System.out.println(list2);
    }

    To answer your first question, Collections doesn't
    know how to sort any ArrayList unless the objects
    implement the Comparable interface and define the
    compareTo method. The String class already defines
    the compareTo method for you, and that's why your
    second ArrayList doesn't require you to write one.
    In your first list you're loading AuctionBid
    references, and Collections can't sort that list
    unless your AuctionBid class implements Comparable
    and defines the compareTo method.
    To answer your second question, System.out.println
    calls toString on the object reference you pass to
    it, unless the reference actually IS a String
    reference. How else could it get a string
    representation of an object without calling toString
    on it?Thank you!
    That makes sense.
    Karl

  • Sort ArrayList on multiple values

    Hi all!
    i'm trying to sort an ArrayList that contains a list of beans with a bunch of properties.
    i think that the comparator should be written like this:
        protected class CategoryComparator implements Comparator {
            public int compare(Object o1, Object o2) {
                Category cat1 = (Category)o1;
                Category cat2 = (Category)o2;
                return cat1.getCategoryName().compareTo(cat2.getCategoryName()) & cat1.getCategoryId().compareTo(cat2.getCategoryId());
        }where Category is the bean, getCategoryName and getCategoryId return two strings. Is that right to get the list sorted on both the two fields?
    Thanks!

    No, it's not. Assuming categoryName is of higher priority, you want int comp = cat1.getCategoryName().compareTo(cat2.getCategoryName());
    if (comp != 0) return comp;
    return cat1.getCategoryId().compareTo(cat2.getCategoryId());

  • Sort Arraylist of hasmaps

    Hi,
    I have Arraylist of Hashmaps, and each hashmap has 10 Key-value pairs.
    How to sort this Arraylist of Hashmaps?
    Any suggestions/ Example?
    Thanks

    What is your criteria for one HashMap coming 'before' or 'after' another? You can create a Comparator which contains those rules and pass it to the sort routine.
    Edit: Sorry, ended up adding nothing to the original answer. If you google "Comparator examples" you'll find some good stuff.
    Edited by: JEisen on Jul 21, 2009 3:49 PM

  • Sort arrayList for integer

    hi,
    some doubts on the syntax
    rows.add(String.valueOf(destList));is this the correct syntax eventhough my "destList" is an integer?
    Collections.sort(rows);i would like to sort my arrayList but it doesnt seem to work with this syntax.the values in my arraylist are in integer.
    please help.thanks

    Maybe a little off topic, but this might be of interest to anyone that wants to sort a 2 dim object array (Object[][]).
    As part of the formatteddataset open source API I have a utility class called ArraySQL. It allows you to issue a reduced sql syntax against an array (i.e. specify a column list, where and order by clauses). The basic idea is that because a 2 dim Array is conceptually similar to a db table you could be able to query it. I will be releasing on sourceforge in a couple weeks, but in the meantime if anyone is interested i can send it to them. Here are some examples
    import com.fdsapi.arrays.ArraySQL;
    Object[][] data{
          {"jim","smith", new Integer(200)}, 
          {"jeff","souza", new Integer(500)},
          {"jim","anderson", new Integer(100)},
          {"stan","jones",new Integer(2000)}};
    ArraySQL asql=new ArraySQL("select * from array where col0 in ('jim', 'jeff') order by col0 asc, col1 desc")
    Object[][] newData=asql.execute(data);
    asql=new ("select * from array order by col2 desc");
    newData=asql.execute(data);steve -
    http://www.fdsapi.com - An easy, fast, extensible way of generating xml and html
    http://www.jamonapi.com - An easy way to monitor application code.
    Both tools are open source and available for download on the given sites.

  • Sorting ArrayList indices

    I am not sure if this can be done. I randomly add elements to ArrayList and arrange in increasing order, can this be done...
    for example,
    ArrayList<String> tempList = new ArrayList <String>();
    tempList.set(o,"aaa");
    tempList,set(3,"bbb");
    tempList.set(1,"ddd");
    tempList.set(2,"ccc");Then I would like to sort them so that I can print them in order, i.e. element at 0, then 1, then 2, then 3....
    How can I do this?

    I am not sure if this can be done. I randomly add
    elements to ArrayList and arrange in increasing
    order, can this be done...
    for example,
    ArrayList<String> tempList = new ArrayList
    <String>();
    tempList.set(o,"aaa");
    tempList,set(3,"bbb");
    tempList.set(1,"ddd");
    tempList.set(2,"ccc");Then I would like to sort them so that I can print
    them in order, i.e. element at 0, then 1, then 2,
    then 3....
    How can I do this?Something says me that [url http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html#sort(java.util.List)]Collections.sort(List list)&#9733; can help you.
    API Documentation is your friend
    ***

  • Jstl sorting Arraylist

    i have used jstl to iterate Arraylist to display car name,price and other details.
    Can anyone help me in sorting out the table based on list box value selected.ie sort by name,sort by model,sort by price,,
    please suggest me ,if it can be done using any taglib
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
    <body>
         <h1>Car List</h1>
    <h1></h1>
    <select>
    <option>Sort by Name</option>
    <option>Sort by Model</option>
    <option>Sort by Price</option>
    </select>
    <table>
         <c:forEach items="${carList}" var="car">
    <tr>
              ${car.brand.name} ${car.model}: ${car.price}
    </tr>     
    </c:forEach>
    </table>
    </body>
    </html>
    ----------------------------------------------------------------------------------------------------------------

    user8619787 wrote:
    i have used jstl to iterate Arraylist to display car name,price and other details.
    Can anyone help me in sorting out the table based on list box value selected.ie sort by name,sort by model,sort by price,,
    please suggest me ,if it can be done using any taglib
    Nope, either have your Car class implement Comparable or else use a Comparator. You need to sort it before setting it to scope for use in the jsp
    cheers,
    ram.

  • Sorting ArrayLists

    How can you sort an ArrayList in ascending order without using the following line of code?
    Collections.sort(myArrayList);I've come up with a bit of code so far, but I have an error message that says "incompatible types" for the two lines that define variables first and second. The code is supposed to be able to sort the ArrayList called "list" in ascending order, and save it into an ArrayList called "list2"... except I can't use that wonderful line of code I mentioned earlier that makes life so much darned easier. The code I'm posting is just the horrible code I have so far for the method that should sort it... all ArrayLists, etc. have been defined and all that good stuff. Any help would be greatly appreciated.
    public static void sorter()
              int count=1;
              list2.add(list.get(0));
              for(int i=0; i<list.size(); i++)
                   for(int f=0; f<list2.size(); f++)
                        int first=list.get(count);
                        int second=list2.get(f);
                        if(first<second)
                             list2.add(0,list.get(count));
                             break;
         }

    Assuming the array holds Objects, you can't just assign them to an int. Try:    // with autoboxing
    // int first=(Integer)list.get(count);
        // without
    int first=((Integer)list.get(count)).intValue();[Edit]Indeed with autoboxingfor(Integer i=0;  // etc...

  • Problems with sort, search and write objects o an ArrayList

    Hi
    Lets say that i have two subclasses (the program is not finished so in the end it can be up to 34 classes) of an abstract superclass. I also got one class which basicly is a register in which i've created an ArrayList of the type <abstractClass>. This means that i store the two subclasses in the arrayList. no problems so far i think (at least eclipse doesn't mind).
    1. now, i want to be able to sort the arrayList aswell as search thorugh it. I've tried Collections.sort(arrayList) but it doesn't work. So i have no idea how to solve that.
    2.The search-method i made doesn't work as good as i hoped for either. I ask the user to first decide what to search for (choose subclass) and then input the same properties as the subclass we search for. I create a new object of the subclass with these inputs and try arrayList.contains(subClassObject)
    it runs but it returns +"false"+ even if i create an object with the exact same properties.
    3. If i want to write this arrayList to a txtFile so i can import it another time. Which is the best method? first i just thought i'd convert the arrayList to string and then print every single object to a textfile as strings. that worked but i have no good idea how to import that into the same arrayList later. Then i found ObjectOutputStream and import using inputStream.nextObject(). But that doesn't work :(
    Any ideas?
    Thank you!
    Anton

    lavalampan wrote:
    Hi
    Lets say that i have two subclasses (the program is not finished so in the end it can be up to 34 classes) of an abstract superclass. I also got one class which basicly is a register in which i've created an ArrayList of the type <abstractClass>. This means that i store the two subclasses in the arrayList. no problems so far i think (at least eclipse doesn't mind).
    1. now, i want to be able to sort the arrayList aswell as search thorugh it. I've tried Collections.sort(arrayList) but it doesn't work. So i have no idea how to solve that. Create a custom comparator.
    >
    2.The search-method i made doesn't work as good as i hoped for either. I ask the user to first decide what to search for (choose subclass) and then input the same properties as the subclass we search for. I create a new object of the subclass with these inputs and try arrayList.contains(subClassObject)
    it runs but it returns +"false"+ even if i create an object with the exact same properties.Implement hashCode and equals.
    >
    3. If i want to write this arrayList to a txtFile so i can import it another time. Which is the best method? first i just thought i'd convert the arrayList to string and then print every single object to a textfile as strings. that worked but i have no good idea how to import that into the same arrayList later. Then i found ObjectOutputStream and import using inputStream.nextObject(). But that doesn't work :(Depends on what your requirement is, but yes, Serialization might work for you. Your classes should in that case implement Serializable.
    Kaj

Maybe you are looking for

  • Error in site-to-server mapping

    I have a Webcache standalone running in load balancer mode. When I try to change something in Site-to-Server Mapping I'm getting the this error: Error This modification would generate an invalid configuration file, thus it is ignored Does someone kno

  • GO URL with Session Variable

    I want to use interaction between two reports in different dashboards, which do not share the same tables but the same values. When clicking on column A values in Report A, I want to create action link with option to open Report B, presenting column

  • Need a FM for change delivery quantity

    Hello, I need a FM to update delivery quantity, I have look for the BAPI BAPI_OUTB_DELIVERY_CONFIRM_DEC but I didn't find how it works. Any help are welcome Frédéric

  • Allocations in FI....?need help....

    Hi, I am not able to understand what is allocation in FI...how to use it... dont understand the functional part very well... Please can someone explain me in detail...meaning of different terms used....transactions used...what will be the flow for it

  • How can i delete bookmarks I no longer need?

    I cannot find anything to click on to delete bookmarks from the menu that I no longer need and my keyboard delete key does nothing to help in this case. I am using a Macbook.