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();

Similar Messages

  • Sort by focal length

    1. Metadata Browser: sort by focal length (using a cushioned range)
    2. Ability to filter based on focal length: i.e. with 3 criteria lens, focal length, aperture it would be super simple to paint in presets for removing natural vignetting.

    Ian,
    The post in which I repeated your comment was not directed at you, the quote was used to re-iterate that it is accepted that the feature is currently not available, and that the search feature is very limited.
    If you feel my post was directed at you, my apologies. If you reread the post, the only two times the word "you" was used was in the following way:
    >"If you build it, they will come..." well, "If the information is there, you should be able to search, filter, or create smart collections by it."
    The comment should have started with "With all due respect to the LR team..." because I hate harping on a subject, with anyone. However, this thread was initiated on July 10, 2007 and covers an issue that deserves to have been addressed by now.
    After all, LR is a database program designed with photographers in mind. All databases work in the same way:
    1. They provide a way to input/gather information
    2. They store the information in fields, and
    3. They allow you to obtain that information through reports, or other means, so you can use it constructively. LR gathers the focal length information separately from the lens information. Therefore, it should be easy to program it to allow you to filter/search/create collections on the information.
    Regards, JML

  • How to Sort by the length of the returned value from a query.

    Hi,
    I was wondering if it is possible to sort by the length of the returned value from a query?
    For example if I want to get a list of people with the name 'Samuel', I would like to short by how short the length of the whole name is.
    Sort by length of the name in SQL
    Samuel Syda
    Samuel Indranaka
    Samuel Johnsons
    Samuel Longhenderson
    Thank you.

    Hi,
    Sorting is done by an ORDER BY clause at the end of the main query.
    In most cases, you can ORDER BY any expression, even f it is not in the SELECT clause.  In this case, it sounds like you just need:
    ORDER BY  LENGTH (name_column)
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
    Post your query, using an ORDER BY clause like the one above, and point out where that query is producing the wrong results, and explain, using specific examples, how you get the right results from the given data in those places.
    Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002

  • 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?

  • OrderedList sorted by String length

    i am trying to create an orderedlist of strings in ascending order by length. I am a little shacky on comparables this is what i have so far. I think i have to implement the Comparable interface and use length as the comparison in the Word class but im not entirely sure how to do this. So for example lion, pig, crocodile should look like ....
    pig
    lion
    crocodile
    in the ordered list... any help is appreciated.
    WORD.JAVA
    public class Word
         private String word, description;
         private int startPos, direction, used;
         public static final int NOTUSED = 0;
         public static final int USED = 1;
         public static final int DOWN= 0;
         public static final int ACROSS= 1;
         public Word(String w, String d)
              word = w;
              description = d;
              //startPos = num;
              //direction = dir;
              //used = use;
         public void setDirection(int dir)
              direction = dir;
         public int getDirection()
              return direction;
         public void setUsed(int use)
              used = use;
         public int getUsed()
              return used;
         public void setPos(int num)
              startPos = num;
         public int getPos()
              return startPos;
         public String getDescription()
              return description;
         public String getWord()
              return word;
         public String toString()
              String str = "";
              str = word+": "+description;
              return str;
    ORDEREDLIST.JAVA
    import java.util.*;
    public class OrderedLinkedList
         private class LinearNode
              private LinearNode next = null;
              private Comparable element = null;
              public LinearNode(Comparable c)
                   element = c;
              public LinearNode getNext()
                   return next;
              public void setNext(LinearNode n)
                   next = n;
              public Comparable getElement()
                   return element;
              public void setElement(Comparable c)
                   element = c;
              public String toStringRecursive()
                   String result = element.toString();
                   if(next == null)
                        return null;
                   else
                        return result + " " + next.toStringRecursive();
              public void add(LinearNode node)
                   if(node.element.compareTo(next.element) <= 0)
                        node.next = next;
                        next = node;
                   else
                        next.add(node);
         private LinearNode first = null;
         private LinearNode last = null;
         private int count = 0;
         public void add(Comparable c)
              LinearNode node = new LinearNode(c);
              if(isEmpty())
                   first = node;
                   last = node;
              else if(count == 1)//(first == last)
                   if(c.compareTo(first.getElement()) > 0) //one in list add to end
                        last = node;
                        first.setNext(last);
                   }else                                   //one in list add to start
                        first = node;
                   first.setNext(last);
              else if(c.compareTo(first.getElement()) <= 0) //multiple in list add to start
                   node.setNext(first);
                   first = node;
              }else if(c.compareTo(last.getElement()) > 0) //multiple in list add to end
                   last.setNext(node);
                   last = node;
              }else
                   first.add(node);
              count++;
         public Comparable remove(Comparable target) throws EmptyStackException,NoSuchElementException
              if(isEmpty())
                   throw new EmptyStackException();
              boolean found = false;
              LinearNode previous = null;
              LinearNode current = first;
              while(current != null && !found)
                   if(target.equals(current.getElement()))
                             found = true;
                   else{
                        previous = current;
                        current = current.getNext();
              if(!found)
                   throw new NoSuchElementException();
              if(size() == 1)
                   first = last = null;
              else if (current.equals(first))
                   first = current.getNext();
                   else if(current.equals(last))
                             last = previous;
                             last.setNext(null);
                        else
                             previous.setNext(current.getNext());
              count--;
              return current.getElement();
         public boolean isEmpty()
              return count == 0;
              //return first == null;
         public String toString()
              String result = "";
              LinearNode current = first;
              while(current != null)
                   result += current.getElement();
                   current = current.getNext();
              return result;
         public int size()
              return count;
    }

    That's rather a lot of code - and much of it has nothing obvious to do with sorting strings by length. Also I can't see where you have implemented the Comparable interface.
    You are talking about java.lang.Comparable, right? In that case some class (Word?) has to be declared as "implements Comparable".
    Another way to do this is is to have an instance of Comparator that you use when you create an ordered collection like a TreeSet.
    Have you read the JavaWorld article: [http://www.javaworld.com/javaworld/jw-12-2002/jw-1227-sort.html]. It is rather old now and doesn't make any use of generics. But it gives examples of a simple collection - a list - being sorted using Collections.sort(). Both the Comparable and Comparator approaches are illustrated

  • 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)

  • Sorting lines by length in automator?

    I have a document with around 4,000 lines of text. Is there a way for me to automatically sort them by character length through the use of Automator and a bit of scripting?
    Bonus points if there's a way to output the character length at the beginning of each line once the sorting is complete.
    Little heads up, my knowledge of AppleScript is pretty non-existant so an idiot's guide would be much appreciated.

    There's nothing wrong with the script, it's the format of your text file that's causing the problem.
    Unfortuntely there isn't really such as thing as a 'plain' text file anymore. Text files come in a variety of formats (ASCII, Unicode, ISO, etc.) and use varying line endings (CR, LF, or CR/LF), and the particular combination used in your file is breaking the script.
    The simplest solution is to save the file as standard UTF-8 Unicode, then the script works fine. If you don't have an application that can convert it you can incorporate the command line utility textutil into your shell command:
    textutil -convert txt -o - $1 | awk '{print (length($0) " " $0 "</sentence>")}' | sort -n
    This time it will invoke textutil to convert the file first (rather than just cat, then run the awk/sort commands.

  • 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

  • Metadata Browser, sort by FOCAL LENGTH

    I'd like to see the option to sort images by focal length, in addition to the by aperture, and by shutter speed.
    //Svien

    In addition, please add the capability sort images in grid view by any meta data item recognized by LR, i.e.: camera model, camera serial number, etc.
    In environments where LR is used to manage images from a variety of shooters and cameras it is extremely useful to be able to sort by meta data via the view:sort order dialog.
    In a high speed workflow environment the work-around of filtering by date range and selecting meta data filters is not desirable.

  • 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.

Maybe you are looking for

  • SOLVED: WiFi dropouts under Windows 7 on Retina Macbook Pro

    I never found the solution to the problem but I found hints around the web. After hours of playing with router settings and driver settings, this problem is solved. Wanted to log down because I did many searches and did not find any clear guidelines.

  • SQL Query in MAxDB..

    Hi Friends, Could you please let me know what should i change to execute the query in MaxDB? select distinct t1.*, iif(t2.id is NULL, 0, 1) as hassub from content t1 left join content t2 on (t1.id=t2.parent_id) where t1.parent_id=" & id & " order by

  • Oracle stored functions and where clauses

    Hello everybody, I need to call an Oracle stored function and at the same time do a select on the result of the query, it works well except when I use a where clause. I am connecting to Oracle 8.1.7 through OLEDB using the Oracle provider for OLEDB d

  • Artwork does not display on iPod

    I have attached artwork to several songs on my iPod library. The artwork is visible in iTunes when I play those songs, but they do not show when I play the songs on my iPod. I have looked over the Support chapters and did everything they told me to:

  • Effects with Software Monitoring off?

    I looked for an answer to this on the forum, but couldn't find one. I prefer to monitor with the "software monitoring" off to avoid the slight latency that occurs. Is there a way to hear some reverb on the input track when in this mode, or what do yo