• The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
Menu
  • The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
  • Sorting Lists in Java

    October 16, 2002 Timothy Prickett Morgan

    Hey, David:

    I have a servlet program that builds a list of products. I have several ways of sorting the list of products, and in most cases, I can just change the order by clause in my select statement to return the correct order. In one view, I need to sort the list by the length of a product component name. I built my own sort routine, but I wonder whether SQL or Java provides a way to sort a list of items by their length.

    — Michael

    You could use a universal disk format (UDF) to return a value to use in your sort, but since you are using Java it makes sense to use the sort facilities provided with the Collections class. The Collections class is part of the collections framework that became available with the 1.2 JDK. In addition to sorting, the Collections class provides static methods that allow you do a multitude of actions, such as search, shuffle, swap, reverse, rotate, retain sets, and remove sets.

    The sort routine provided by the Collections class is also very fast. The Collections sort routine is a merge sort that is far more efficient than a quick sort or bubble sort. Here is an example that sorts a list of string values first by length and then by the string value:

    package demo;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.Iterator;
    
    
    /**
     * Class LengthSort shows how to sort a list by the length of its values.
     * @author David Morris
     */
    public class LengthSort {
        public static void main(String[] args) {
            ArrayList values = new ArrayList();
    
            values.add("one");
            values.add("two");
            values.add("three");
            values.add("four");
            values.add("five");
            values.add("six");
    
            Iterator i = values.iterator();
            System.out.println("Before:");
    
            while (i.hasNext())
                System.out.println(i.next());
    
            Collections.sort(values, new Comparator() {
                public int compare(Object o1, Object o2) {
                    String s1 = (String) o1;
                    String s2 = (String) o2;
    
                    if (s1.length() < s2.length()) {
                        return -1;
                    }
                    else if (s1.length() > s2.length()) {
                        return 1;
                    }
                    else {
                        return s1.compareTo(s2);
                    }
                }
            });
    
            i = values.iterator();
            System.out.println("nAfter:");
    
            while (i.hasNext())
                System.out.println(i.next());
        }
    }
    

    Running this program generates the following list:

    Before:
    one
    two
    three
    four
    five
    six

    After:
    one
    six
    two
    five
    four
    three

    Passing a comparator to Collections.sort allows you to sort a list in any order. The comparator returns a negative 1 (-1) to indicate that the first value is less than the second, a zero (0) when both values are equal, and a positive 1 (+1) when the first value is greater than the second.

    — David

    Sponsored By
    ADVANCED SYSTEMS CONCEPTS

    SEQUEL meets all your iSeries and AS/400 data access needs in a single, integrated solution:

    • Windows, Web or host user interfaces

    • Convert AS/400 data into PC file formats

    • E-mail or FTP query results, reports and spool files
    • Run-time prompted queries and reports for end users

    • IF-THEN-ELSE logic in queries and reports

    • Report, form and label formatting second to none

    • Easily convert date fields, character-to-numeric, numeric-to-character and other data manipulation

    • SORT or JOIN using a calculated field

    • Quick summarization of data with Tabling function

    • Run multiple SEQUEL requests as one with the SEQUEL Scripting function

    • OLAP Business Intelligence at a fraction of the cost of comparable solutions

    Take 6 minutes to view a SEQUEL ViewPoint ScreenCam movie to see how simple Windows-based AS/400 and iSeries data access can be! In just a few short minutes, you can find out ways to make your job easier and improve data access throughout your organization. Download the ViewPoint movie here .

    For more information or a FREE trial of SEQUEL, call 847/605-1311 or visit Advanced Systems Concepts.

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Tags: Tags: mgo_rc, Volume 2, Number 79 -- October 16, 2002

    Sponsored by
    FalconStor

    Begin Your Journey to the Cloud with Hybrid Cloud Date Protection and Disaster Recovery

    FalconStor StorSafe optimizes and modernizes your IBM i on-premises and in the IBM Power Virtual Server Cloud

    FalconStor powers secure and encrypted IBM i backups on-premise and now, working with IBM, powers migration to the IBM PowerVS cloud and on-going backup to IBM cloud object storage.

    Now you can use the IBM PowerVS Cloud as your secure offsite copy and take advantage of a hybrid cloud architecture or you can migrate workloads – test & development or even production apps – to the Power VS Cloud with secure cloud-native backup, powered by FalconStor and proven IBM partners.

    Learn More

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Client Access Hotspots Reader Feedback and Insights: Another Compression Utility

    Leave a Reply Cancel reply

MGO Volume: 2 Issue: 79

This Issue Sponsored By

    Table of Contents

    • Reader Feedback and Insights: Dynamic Result Field in Query/400
    • Sorting Lists in Java
    • Extending the Network

    Content archive

    • The Four Hundred
    • Four Hundred Stuff
    • Four Hundred Guru

    Recent Posts

    • With Power11, Power Systems “Go To Eleven”
    • With Subscription Price, IBM i P20 And P30 Tiers Get Bigger Bundles
    • Izzi Buys CNX, Eyes Valence Port To System Z
    • IBM i Shops “Attacking” Security Concerns, Study Shows
    • IBM i PTF Guide, Volume 27, Number 26
    • Liam Allan Shares What’s Coming Next With Code For IBM i
    • From Stable To Scalable: Visual LANSA 16 Powers IBM i Growth – Launching July 8
    • VS Code Will Be The Heart Of The Modern IBM i Platform
    • The AS/400: A 37-Year-Old Dog That Loves To Learn New Tricks
    • IBM i PTF Guide, Volume 27, Number 25

    Subscribe

    To get news from IT Jungle sent to your inbox every week, subscribe to our newsletter.

    Pages

    • About Us
    • Contact
    • Contributors
    • Four Hundred Monitor
    • IBM i PTF Guide
    • Media Kit
    • Subscribe

    Search

    Copyright © 2025 IT Jungle