• 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
    Midrange Dynamics North America

    Want to deliver DevOps on IBM i?

    DevOps enables your IBM i development teams to shorten the software development lifecycle while delivering features, fixes, and frequent updates that are closely aligned with business objectives. Flexible configuration options within MDChange make it easy to adapt to new workflow strategies and policies as you adopt DevOps practices across your organization.

    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

    • The Power11 Transistor Count Discrepancies Explained – Sort Of
    • Is Your IBM i HA/DR Actually Tested – Or Just Installed?
    • Big Blue Delivers IBM i Customer Requests In ACS Update
    • New DbToo SDK Hooks RPG And Db2 For i To External Services
    • IBM i PTF Guide, Volume 27, Number 33
    • Tool Aims To Streamline Git Integration For Old School IBM i Devs
    • IBM To Add Full System Replication And FlashCopy To PowerHA
    • Guru: Decoding Base64 ASCII
    • The Price Tweaking Continues For Power Systems
    • IBM i PTF Guide, Volume 27, Numbers 31 And 32

    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