How to Use the Comparator.comparing Method in Java 8

  • google plus

In Brief...

The Comparator.comparing method, introduced in Java 8, returns a Comparator object that will use the specified field as the sort key. The Comparator interface is a functional interface in Java 8, and the method implemented is the compare method. Therefore, the compare method is implemented by the comparing method using the specified key. To learn how to use the Comparator.comparing method, follow these seven steps.

Take our Introduction to Java Training course for free.

See the Course Outline and Register

Instructions

  1. Open your text editor and create a new file that will contain the musical instrument class that ultimately will be sorted. Type in the following Java statements:
    public class MusicalInstrument {
    	private String name;
    	private String type;
    	public MusicalInstrument(String name, String type) {
    		setName(name);
    		setType(type);
    	}	
    	public String getName() {
    		return name;
    	}
    	public void setName (String name) {
    		this.name=name;
    	}
    	public String getType() {
    		return type;
    	}
    	public void setType (String type) {
    		this.type=type;
    	}
    	public String toString() {
    		return name + " is a " + type + " instrument";
    	}
    }
    This is a straightforward Java bean that contains two properties: musical instrument name (e.g., trumpet) and type of musical instrument (e.g., brass). I have highlighted the two properties in the image below:
    Java Source for Musical Instrument
  2. Save your file as MusicalInstrument.java.
  3. Open a command prompt and navigate to the directory containing your new Java program. Then type in the command to compile the source and hit Enter.
    Compile Source for Musical Instrument
  4. Open your text editor and create the Java program that will demonstrate the use of the Comparator.comparing method. Type in the following Java statements:
    
    import java.util.stream.*;
    import java.util.*;
    public class UseComparatorcomparingMethod {
    	private static List musicalInstruments=new ArrayList<>();
    	static {
    		musicalInstruments.add(new MusicalInstrument("Trumpet","brass"));
    		musicalInstruments.add(new MusicalInstrument("Tuba","brass"));
    		musicalInstruments.add(new MusicalInstrument("Timpani","percussion"));
    		musicalInstruments.add(new MusicalInstrument("Piano","keyboard"));
    	}
    	public static void main (String args[]) {
    		System.out.println("Musical instruments in the collection sorted by name:");
    		Collections.sort(musicalInstruments, Comparator.comparing((MusicalInstrument instrument) -> instrument.getName()));
    		musicalInstruments.stream().forEach(System.out::println);
    		
    		System.out.println("Musical instruments in the collection sorted by type:");
    		Collections.sort(musicalInstruments, Comparator.comparing((MusicalInstrument instrument) -> instrument.getType()));
    		musicalInstruments.stream().forEach(instrument->System.out.println(instrument));
    	}
    }
    The stream will be created from the ArrayList that is defined on line 4. Note that a static block is used to add elements to the ArrayList. A static block is executed one time when the program is loaded into memory. The ArrayList will be sorted by Collections.sort. This static method accepts an ArrayList and a Comparator object. Note that the Comparator object will be returned by the comparing method. The parameter passed to the comparing method is a lambda expression that determines the sort field. The musical instrument name is passed to the first comparing method and the musical instrument type is passed to the second comparing method. I have highlighted the comparing method calls below:
    Java Source for Comparing Method
  5. Save your file as UseComparatorcomparingMethod.java.
  6. Open a command prompt and navigate to the directory containing your new Java program. Then type in the command to compile the source and hit Enter.
    Compile Program with Comparing Method
  7. You are ready to test your Java program. Type in the command to run the Java runtime launcher and hit Enter. The output displays the musical instruments sorted first by name and then by type.
    Run Program with Comparing Method

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss