JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Program: How to sort an array using comparator?


Description:

Java Arrays class provides few utility methods. One of the utility method Arrays.sort() helps us to sort an Array of objects by passing Comparator object, where Comparator holds the sorting logic. Below example shows how to sort an array using Comparator.


Code:
package com.java2novice.arrays;

import java.util.Arrays;
import java.util.Comparator;

public class MyStringArraySorting {

	public static void main(String a[]){
		
		String[] strArr = {"JAVA", "C++", "PERL", "STRUTS", "PLAY"};
		Arrays.sort(strArr,new Comparator<String>(){

			@Override
			public int compare(String o1, String o2) {
				return o1.compareTo(o2);
			}});
		
		for(String str:strArr){
			System.out.println(str);
		}
	}
}

Output:
C++
JAVA
PERL
PLAY
STRUTS
<< Previous Program 
Knowledge Centre
What is adapter class?
An adapter class provides the default implementation of all methods in an event listener interface. Adapter classes are very useful when you want to process only few of the events that are handled by a particular event listener interface. You can define a new class by extending one of the adapter classes and implement only those events relevant to you.
Famous Quotations
I don’t know the key to success, but the key to failure is trying to please everybody.
-- Bill Cosby

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.