Sparkles

that were shone when I got tempered!

Sorting Collections in Java

leave a comment »

Sorting an ArrayList of Strings alphabetically.

This is pretty simple with the Collection.sort() as follows.

package collections.sorting;

import java.util.*;

class TestSort1 {

	public static void main(String[] args) {
		
		ArrayList<String> 	stuff 	= new ArrayList<String>();
		stuff.add("Denver");
		stuff.add("Boulder");
		stuff.add("Vail");
		stuff.add("Aspen");
		stuff.add("Telluride");
		
		System.out.println("unsorted " + stuff);
		
		Collections.sort(stuff);
		System.out.println("sorted" + stuff);
	}
	
}

This prints
unsorted [Denver, Boulder, Vail, Aspen, Telluride]
sorted [Aspen, Boulder, Denver, Telluride, Vail]

Sorting an ArrayList of — we created — DVDInfos.

DVDInfo.java


package collections.sorting.dvdInfo;

class DVDInfo {
	
	String title;
	String genre;
	String leadActor;
	
	DVDInfo(String t, String g, String a) {

		title = t; genre = g; leadActor = a;
	}
	
	public String toString() {
		return title + " " + genre + " " + leadActor + "\n";
	}

}

In another client class,

</pre>
ArrayList<DVDInfo> dvdInfoList = new ArrayList<DVDInfo>();
Collections.sort(dvdInfoList);

Throws an error –
Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (ArrayList<DVDInfo>). The inferred type DVDInfo is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>.

Reason –
The sort() method takes a List argument, and that the objects in the List must implement an interface called Comparable. It turns out that String implements Comparable, and that’s why we were able to sort a list of Strings using the Collections.sort() method.

 

The Comparable Interface

The Comparable interface is used by the Collections.sort() method and the java.util.Arrays.sort() method to sort Lists and arrays of objects, respectively. To implement Comparable , a class must implement a single method,compareTo() .

Here’s an invocation of compareTo() :

</pre>
int x = thisObject.compareTo(anotherObject);

The compareTo() method returns an int with the following characteristics:

  • negative : If thisObject < anotherObject
  • zero : If thisObject == anotherObject
  • positive : If thisObject > anotherObject

So, we can change the DVDInfo.java class like this to make it comparable

package collections.sorting.dvdInfo;

class DVDInfo implements Comparable<DVDInfo>{

	DVDInfo(String t, String g, String a) {
		
		title = t; genre = g; leadActor = a;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String toString() {
		return title + " " + genre + " " + leadActor + "\n";
	}

	public int compareTo(DVDInfo d) {
		return title.compareTo(d.getTitle());
	}

	String title;
	String genre;
	String leadActor;

}

This actually makes it comparable.
But, we’ll probably want to sort DVD collections in lots of different ways. Since we sorted our ArrayList by implementing the compareTo() method, we seem to be stuck. So, there must be another way to do this – which is comming up next – .

Sorting with Comparator

The Comparator interface gives you the capability to sort a given collection any number of different ways. The other handy thing about the Comparator interface is that you can use it to sort instances of any class—even classes you can’t modify —unlike the Comparable interface, which forces you to change the class whose instances you want to sort. The Comparator interface is also very easy to implement, having only one method, compare() . Here’s a small class that can be used to sort a List of DVDInfo instances, by genre

class GenreSort implements Comparator<DVDInfo> {

	public int compare(DVDInfo one, DVDInfo two) {
	
		return one.getGenre().compareTo(two.getGenre());
	
	}

}

So, now we can sort it without touching DVDInfo class (to implemnet the Comparable and override compareTo method in there) like follows.

GenreSort genreSort = new GenreSort();
Collections.sort(dvdInfoList, genreSort);

Screenshot from 2015-04-15 14:19:54Reference :

  • SCJP
Advertisements

Written by Namal Fernando

April 15, 2015 at 2:17 pm

Posted in Java

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Ruth's Reflections

Contemplations from quakey quirky Christchurch

TED Blog

The TED Blog shares interesting news about TED, TED Talks video, the TED Prize and more.

Ziplok

Learn and discover simple things

Meihta Dwiguna Saputra's Knowledge Base

~In learning you will teach and in teaching you will (re)learn~

The Java Blog

Thoughts, tips and tricks about the Java programming language

Sparkles

that were shone when I got tempered!

%d bloggers like this: