473,382 Members | 1,689 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

sorting objects in arraylist in java

How can I sort objects in an arraylist based on a particular field of the object.
my arraylist has a collection of objects. each object has one of the fields as name. now i want to sort the objects in alphabetical order of names. how do i do dat
Oct 26 '06 #1
2 30569
r035198x
13,262 8TB
How can I sort objects in an arraylist based on a particular field of the object.
my arraylist has a collection of objects. each object has one of the fields as name. now i want to sort the objects in alphabetical order of names. how do i do dat
If you can control how objects get into the list, you can make sure that the objects get in sorted(insertion sort). If you already have an unsorted list, then you need to write the sort function to sort that. Are you asking for the sort function?
Oct 27 '06 #2
r035198x
13,262 8TB
This will allow you as many sorts as are compare methods defined for your object:
Expand|Select|Wrap|Line Numbers
  1. import java.util.*;
  2. class Church {
  3.     private String name;
  4.     private String pastor;
  5.     public Church(String name, String pastor) {
  6.         this.name = name;
  7.         this.pastor = pastor;
  8.     }
  9.     public String getPastor() {
  10.         return pastor;
  11.     }
  12.     public String getName() {
  13.         return name;
  14.     }
  15.     public void setPastor(String pastor) {
  16.         this.pastor = pastor;
  17.     }
  18.     public String toString() {
  19.         return getName() + " is Pastored by "+getPastor();
  20.     }
  21.     public int compareByPastor(Church c) {
  22.         int x = pastor.compareTo(c.getPastor());
  23.         return x;
  24.     }
  25.     public int compareByName(Church c) {
  26.         int x = name.compareTo(c.getName());
  27.         return x;
  28.     }
  29. }
  30.  
  31. class Churches {
  32.     private final List<Church> churches;
  33.  
  34.     public Churches() {
  35.         churches = new ArrayList<Church>();
  36.     }
  37.     public void addWithoutSorting(Church c) {
  38.         churches.add(c);
  39.     }
  40.  
  41.     //You could always add using this method
  42.     public void addWithSorting(Church c) {
  43.  
  44.     }
  45.     public void display() {
  46.         for(int j = 0; j < churches.size(); j++) {
  47.             System.out.print(churches.get(j).toString());
  48.             System.out.println("");
  49.         }
  50.    }
  51.    public List<Church> getChurches() {
  52.        return churches;
  53.    }
  54.    public void sortBy(String s) {
  55.        for (int i = 1; i < churches.size(); i++) {
  56.            int j;
  57.            Church val = churches.get(i);
  58.            for (j = i-1; j > -1; j--) {
  59.                Church temp = churches.get(j);
  60.                if(s.equals("Pastor")) {
  61.                    if (temp.compareByPastor(val) <= 0) {
  62.                        break;
  63.                    }
  64.                }
  65.                else if(s.equals("Name")) {
  66.                    if (temp.compareByName(val) <= 0) {
  67.                           break;
  68.                    }
  69.                }
  70.                churches.set(j+1, temp);
  71.             }
  72.             churches.set(j+1, val);
  73.        }
  74.      }
  75.  
  76.     public static void main(String[] args) {
  77.         Churches baptists = new Churches();
  78.         baptists.addWithoutSorting(new Church("Pac", "Pastor G"));
  79.         baptists.addWithoutSorting(new Church("New Life", "Tudor"));
  80.         baptists.addWithoutSorting(new Church("My Church", "r035198x"));
  81.         baptists.addWithoutSorting(new Church("AFM", "Cathy"));
  82.         System.out.println("**********************Before Sorting***********************");
  83.         baptists.display();
  84.         baptists.sortBy("Pastor");
  85.         System.out.println("**********************After sorting by Pastor**************");
  86.         baptists.display();
  87.         baptists.sortBy("Name");
  88.         System.out.println("**********************After sorting by Name****************");
  89.         baptists.display();
  90.  
  91.     }
  92.  
  93.   }
Oct 27 '06 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Nick | last post by:
Hi ! I have Objects in my ArrayList These Objects contain a String called "Name". And i want that ArrayList to sort it's objects using the Name element of each object and not something else of...
7
by: ryba | last post by:
Hello I'm sorry for mistakes - my English isn't very well. I've got the problem with sorting objects in ArrayList. If I put there only strings, Sort method works great, but it doesnt work when I...
3
by: Derek Martin | last post by:
Hi there, I've asked before but never got an answer that could get me completely to where I was heading. I have an arraylist that contains defined objects and I would like to sort this arraylist...
2
by: Adam | last post by:
Hi, I've got a class which contains a number of properties which in turn are read from a database. For example: class TData public property firstName <get and set here> public property...
7
by: Derek Martin | last post by:
Hi there, I've asked before but never got an answer that could get me completely to where I was heading. I have an arraylist that contains defined objects and I would like to sort this arraylist...
1
by: Kiran | last post by:
how to send and recieve objects to java web services from .net client
16
by: RCS | last post by:
So I have an ArrayList that gets populated with objects like: myAL.Add(new CustomObject(parm1,parm2)); I'm consuming this ArrayList from an ObjectDataSource and would like to have this support...
12
by: Justin | last post by:
Ok, I give up. I can't seem to construct a decent (productive) way of sorting my arraylist. I have a structure of two elements: Structure TabStructure Dim TabName As String Dim FullFilePath...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.