Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 481251
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T00:58:32+00:00 2026-05-13T00:58:32+00:00

I am looking to implement a sort feature for my address book application. I

  • 0

I am looking to implement a sort feature for my address book application.

I want to sort an ArrayList<Contact> contactArray. Contact is a class which contains four fields: name, home number, mobile number and address. I want to sort on name.

How can I write a custom sort function to do this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T00:58:33+00:00Added an answer on May 13, 2026 at 12:58 am

    Here’s a tutorial about ordering objects:

    • The Java Tutorials – Collections – Object Ordering

    Although I will give some examples, I would recommend to read it anyway.


    There are various way to sort an ArrayList. If you want to define a natural (default) ordering, then you need to let Contact implement Comparable. Assuming that you want to sort by default on name, then do (nullchecks omitted for simplicity):

    public class Contact implements Comparable<Contact> {
    
        private String name;
        private String phone;
        private Address address;
    
        @Override
        public int compareTo(Contact other) {
            return name.compareTo(other.name);
        }
    
        // Add/generate getters/setters and other boilerplate.
    }
    

    so that you can just do

    List<Contact> contacts = new ArrayList<Contact>();
    // Fill it.
    
    Collections.sort(contacts);
    

    If you want to define an external controllable ordering (which overrides the natural ordering), then you need to create a Comparator:

    List<Contact> contacts = new ArrayList<Contact>();
    // Fill it.
    
    // Now sort by address instead of name (default).
    Collections.sort(contacts, new Comparator<Contact>() {
        public int compare(Contact one, Contact other) {
            return one.getAddress().compareTo(other.getAddress());
        }
    }); 
    

    You can even define the Comparators in the Contact itself so that you can reuse them instead of recreating them everytime:

    public class Contact {
    
        private String name;
        private String phone;
        private Address address;
    
        // ...
    
        public static Comparator<Contact> COMPARE_BY_PHONE = new Comparator<Contact>() {
            public int compare(Contact one, Contact other) {
                return one.phone.compareTo(other.phone);
            }
        };
    
        public static Comparator<Contact> COMPARE_BY_ADDRESS = new Comparator<Contact>() {
            public int compare(Contact one, Contact other) {
                return one.address.compareTo(other.address);
            }
        };
    
    }
    

    which can be used as follows:

    List<Contact> contacts = new ArrayList<Contact>();
    // Fill it.
    
    // Sort by address.
    Collections.sort(contacts, Contact.COMPARE_BY_ADDRESS);
    
    // Sort later by phone.
    Collections.sort(contacts, Contact.COMPARE_BY_PHONE);
    

    And to cream the top off, you could consider to use a generic javabean comparator:

    public class BeanComparator implements Comparator<Object> {
    
        private String getter;
    
        public BeanComparator(String field) {
            this.getter = "get" + field.substring(0, 1).toUpperCase() + field.substring(1);
        }
    
        public int compare(Object o1, Object o2) {
            try {
                if (o1 != null && o2 != null) {
                    o1 = o1.getClass().getMethod(getter, new Class[0]).invoke(o1, new Object[0]);
                    o2 = o2.getClass().getMethod(getter, new Class[0]).invoke(o2, new Object[0]);
                }
            } catch (Exception e) {
                // If this exception occurs, then it is usually a fault of the developer.
                throw new RuntimeException("Cannot compare " + o1 + " with " + o2 + " on " + getter, e);
            }
    
            return (o1 == null) ? -1 : ((o2 == null) ? 1 : ((Comparable<Object>) o1).compareTo(o2));
        }
    
    }
    

    which you can use as follows:

    // Sort on "phone" field of the Contact bean.
    Collections.sort(contacts, new BeanComparator("phone"));
    

    (as you see in the code, possibly null fields are already covered to avoid NPE’s during sort)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm looking to implement something in Java along the lines of: class Foo{ private
I'm looking to implement a Contact Us form with Cherrypy and was wondering: Is
We are looking to implement Optimistic locking in our WCF/WPF application. So far the
I am looking to implement a sort of 'activity log' table where actions a
I'm looking to implement httpOnly in my legacy ASP classic sites. Anyone knows how
I am looking to implement a data-driven wizard with the question tree stored in
I am looking to implement horizontal scrolling using jQuery.SerialScroll (based on jQuery.ScrollTo ). I
I am looking to implement (or build as a last resort) a type of
I am looking to implement a live search in my MVC app similar to
I'm looking to implement user login onto my site for the first time. I'm

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.