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
Java class can be private?
We can not declare top level class as private. Java allows only public and default modifier for top level classes in java. Inner classes can be private.
Famous Quotations
When I do good, I feel good; when I do bad, I feel bad, and that is my religion.
-- Abraham Lincoln

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.