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
Procedural Vs Object-oriented Programs
In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code.

In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code.
Famous Quotations
Before you go and criticize the younger generation, just remember who raised them.
-- Unknown Author

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.