• 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
    VISUAL LANSA 16 WEBINAR

    Trying to balance stability and agility in your IBM i environment?

    Join this webinar and explore Visual LANSA 16 – our enhanced professional low-code platform designed to help organizations running on IBM i evolve seamlessly for what’s next.

    🎙️VISUAL LANSA 16 WEBINAR

    Break Monolithic IBM i Applications and Unlock New Value

    Explore modernization without rewriting. Decouple monolithic applications and extend their value through integration with modern services, web frameworks, and cloud technologies.

    🗓️ July 10, 2025

    ⏰ 9 AM – 10 AM CDT (4 PM to 5 PM CEST)

    See the webinar schedule in your time zone

    Register to join the webinar now

    What to Expect

    • Get to know Visual LANSA 16, its core features, latest enhancements, and use cases
    • Understand how you can transition to a MACH-aligned architecture to enable faster innovation
    • Discover native REST APIs, WebView2 support, cloud-ready Azure licensing, and more to help transform and scale your IBM i applications

    Read more about V16 here.

    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

    • 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
    • Meet The Next Gen Of IBMers Helping To Build IBM i
    • Looks Like IBM Is Building A Linux-Like PASE For IBM i After All
    • Will Independent IBM i Clouds Survive PowerVS?
    • Now, IBM Is Jacking Up Hardware Maintenance Prices
    • IBM i PTF Guide, Volume 27, Number 24

    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